所以我试图 $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>
最佳答案
对象=新的ObjectService();
由于 Javascript 中参数传递给函数的方式而无法工作。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
就您而言,您可以为 $scope.newObject 分配一个新的空对象。
$scope.newObject = new ObjectService();
您甚至不需要参数,因为您可以使用变量 $scope.newObject 来调用资源方法。
关于javascript - 在 ngResource $save 之后操作保存的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865810/