我是AngularJs的初学者,我试图了解$resource
服务。
对资源实例对象调用delete
操作,如下所示:
$scope.deleteTask = function(task) {
task.$delete(function(tasks) {
$scope.tasks = tasks;
}, function() {
});
};
引发此异常:
TypeError: undefined is not a function
at http://localhost:3030/libs/angular-resource/angular-resource.js:557:27
at forEach (http://localhost:3030/libs/angular/angular.js:325:18)
at $http.then.value.$resolved (http://localhost:3030/libs/angular-resource/angular-resource.js:555:17)
at wrappedCallback (http://localhost:3030/libs/angular/angular.js:11573:81)
at wrappedCallback (http://localhost:3030/libs/angular/angular.js:11573:81)
at http://localhost:3030/libs/angular/angular.js:11659:26
at Scope.$eval (http://localhost:3030/libs/angular/angular.js:12702:28)
at Scope.$digest (http://localhost:3030/libs/angular/angular.js:12514:31)
at Scope.$apply (http://localhost:3030/libs/angular/angular.js:12806:24)
at done (http://localhost:3030/libs/angular/angular.js:8379:45)
知道我将工厂定义为:
(function() {
var Task = function($resource, RestUrls) {
return $resource(RestUrls.one, {}, {
"save": {
method: "POST",
isArray: true
},
"put": {
method: "PUT",
url: RestUrls.put,
params: { id: "@_id" },
isArray: true
},
"delete": {
url: RestUrls.delete,
params: { id: "@_id" },
method: "DELETE",
isArray: true
}
});
};
angular.module("TaskApp").factory("Task", ["$resource", "RestUrls", Task]);
})();
在资源类上调用它时正常工作:
$scope.deleteTask = function(task) {
Task.delete({ id: task._id }, function(tasks) {
$scope.tasks = tasks;
}, function() {
});
};
最后,这里是调用deleteTask(task)
的HTML:
<ul>
<li ng-repeat="task in tasks">
<span>{{ task.content }}</span>
<a href="#/{{ task._id }}">Edit</a>
<button ng-click="deleteTask(task)">Delete</button>
</li>
</ul>
这里是删除操作的服务器端代码(在node.js中):
deleteTask: function(req, res, next) {
Task.remove({ _id: req.params.id }, function(err, affected) {
if(err) return next(err);
Task.find({}, function(err, tasks) {
if(err) return next(err);
res.json(tasks);
});
});
}