I am learning Angularjs and using Restangular to connect to Rails server API. I seem to be lacking a basic understanding of how to assign parameters from a form to a var that I will use in my function to post to my rails API.
Here is my controller (or the relevant portion):
.controller('NewCtrl', ["$scope", "Restangular", function($scope, Restangular) {
var passages = Restangular.all('passages');
var allPassages = passages.getList();
var newPassage = {
book: $scope.passages.book
};
$scope.add = function() {
passages.post(newPassage);
};
Here is my form:
<h1>Add New Passage</h1>
<form name="myForm" ng-submit="add()" ng-controller="NewCtrl" class="my-form">
Book: <input name="passages.book" required><span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<input type="submit" id="submit" value="Submit" />
</form>
In the javascript console I get the following error:
TypeError: Cannot read property 'book' of undefined
at new <anonymous> (http://localhost:9000/scripts/controllers/main.js:38:27)
at invoke (http://localhost:9000/bower_components/angular/angular.js:3000:28)
at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3012:23)
at http://localhost:9000/bower_components/angular/angular.js:4981:24
at update (http://localhost:9000/bower_components/angular/angular.js:14509:26)
at Object.Scope.$broadcast (http://localhost:9000/bower_components/angular/angular.js:8468:28)
at http://localhost:9000/bower_components/angular/angular.js:7614:26
at wrappedCallback (http://localhost:9000/bower_components/angular/angular.js:6995:59)
at wrappedCallback (http://localhost:9000/bower_components/angular/angular.js:6995:59)
at http://localhost:9000/bower_components/angular/angular.js:7032:26
I think I am missing something in how I can assign values from my form with $scope to a value in my var. When I assign a literal value of say: book: "Ephesians" it works just fine. Thanks for help with this question.
Here is how to fix your controller:
.controller('NewCtrl', ["$scope", "Restangular", function($scope, Restangular) {
var passages = Restangular.all('passages');
var allPassages = passages.getList();
// Initialise $scope.passage:
$scope.passages = {
book: null
};
$scope.add = function() {
passages.post({
book: $scope.passages.book
});
};
}])
and the markup:
<h1>Add New Passage</h1>
<form name="myForm" ng-submit="add()" ng-controller="NewCtrl" class="my-form">
Book: <input ng-model="passages.book" name="passages.book" required><span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<input type="submit" id="submit" value="Submit" />
</form>