所以我试图$保存一个对象,然后清空它的值。

我有:

$scope.newObject = new ObjectService()

$scope.saveObject = function(objectToSave)


所以ng-click="saveObject(newObject)调用该函数传递对象,然后在$ save完成后尝试清空它的值。我要这样做的方法是再次将objectToSave初始化为new ObjectService()(就像在$ save()之前一样)。问题在于它只是行不通(我知道这可能与Javascript基础有关,我只是不知道它是什么)。

请检查下面的代码段。代码注释更好地解释了我的问题。

请注意 ! :我正在尝试处理.error()函数中$ save的响应,因为这是一个示例。



angular.module('app', ['ngResource'])
  .controller('ctrl', ['$scope', 'ObjectService',
    function($scope, ObjectService) {
      $scope.newObject = new ObjectService();
      $scope.newObject.foo = 'something';

      $scope.saveObject = function(object) {
        object.$save(function() {
          // won't success in this example..
        }, function() {
          //object.foo = '...'; // This works fine.
          object = new ObjectService();
          // $scope.newObject shouldn't be a new ObjectService now? So $scope.newObject.foo should be an empty string

        });
      };
    }
  ])
  .factory('ObjectService', ['$resource',
    function($resource) {
      return $resource('http://somewhere/something', {
        foo: '@foo'
      });
    }
  ]);

<html ng-app="app">

<body ng-controller="ctrl">
  <input type="text" ng-model="newObject.foo">
  <button type="button" ng-click="saveObject(newObject)">Save</button>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <script src="https://code.angularjs.org/1.3.15/angular-resource.min.js"></script>
</body>

</html>

最佳答案

object = new ObjectService();

无法使用,因为参数传递给Javascript函数的方式。见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

您可以为$ scope.newObject分配一个新的空对象。

$ scope.newObject =新的ObjectService();

您甚至不需要参数,因为您可以使用变量$ scope.newObject调用资源方法。

关于javascript - 在ngResource $ save之后处理保存的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29865810/

10-12 12:43
查看更多