使用Restangular并尝试将多个参数设置为$ scope的var

时间:2014-08-20 12:23:16

标签: javascript ruby-on-rails angularjs restangular

我正在学习Angularjs并使用Restangular连接到Rails服务器API。我似乎缺乏对如何将表单中的参数分配给var的基本理解,我将在函数中使用这些参数发布到我的rails API。

这是我的控制器(或相关部分):

.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);
  };

这是我的表格:

<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>

在javascript控制台中,我收到以下错误:

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 

我认为我错过了一些关于如何将带有$ scope的表单中的值赋值给我的var中的值。当我分配一个文字值say:book:“Ephesians”时,它运作得很好。感谢您对此问题的帮助。

1 个答案:

答案 0 :(得分:1)

以下是修复控制器的方法:

.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
        });
    };
}])

和标记:

<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>