在 ngResource $save 之后操作保存的对象



所以我试图$save一个对象并在之后清空它的值。

我有:

$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 = new ObjectService();

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

最新更新