使用Restangular并尝试从$scope中为一个var设置多个参数

Using Restangular and trying to set multiple parameters to a var from $scope

本文关键字:一个 var 参数 设置 Restangular scope 使用      更新时间:2023-09-26

我正在学习Angularjs和使用Restangular连接到Rails服务器API。我似乎缺乏一个基本的了解如何从一个形式分配参数到一个变量,我将在我的函数中使用到我的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中的值中缺少了一些东西。当我分配一个文字值说:book:"以弗所书"时,它工作得很好。谢谢你对这个问题的帮助

如何修复你的控制器:

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