我正在学习如何从示例中使用解析,并将其应用于我的 Todo 脚本。
然后我意识到一个问题,该示例仅向我展示了当我第一次访问此路线时如何解决 GET 调用以获取待办事项列表。
但是,在同一路线的同一页面中,我有一个添加按钮来发布新的待办事项,还有一个清除按钮来删除已完成的项目。
看着我$scope.addTodo = function() {
,$scope.clearCompleted = function () {
我想在行动后再次解决我的 TodoList。我怎样才能做到这一点?
这是我的代码。在我的代码中,初始resolve: { todos: TodosListResl }
值是有效的,它会触发TodosListResl
函数并产生承诺。但是,我不知道如何处理addTodo
以及clearComplete
何时再次解决待办事项列表。
main.js
var todoApp = angular.module('TodoApp', ['ngResource', 'ui']);
todoApp.value('restTodo', 'api/1/todo/:id');
todoApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when("/", { templateUrl: "Templates/_TodosList.html",
controller: TodosListCtrl, resolve: { todos: TodosListResl } });
$routeProvider.otherwise({ redirectTo: '/' });
});
//copied from example, works great
function TodoCtrl($scope, $rootScope, $location) {
$scope.alertMessage = "Welcome";
$scope.alertClass = "alert-info hide";
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$scope.alertMessage = "Loading...";
$scope.alertClass = "progress-striped active progress-warning alert-info";
});
$rootScope.$on("$routeChangeSuccess", function (event, current, previous) {
$scope.alertMessage = "OK";
$scope.alertClass = "progress-success alert-success hide";
$scope.newLocation = $location.path();
});
$rootScope.$on("$routeChangeError",
function (event, current, previous, rejection) {
alert("ROUTE CHANGE ERROR: " + rejection);
$scope.alertMessage = "Failed";
$scope.alertClass = "progress-danger alert-error";
});
}
//also copied from example, works great.
function TodosListResl($q, $route, $timeout, $resource, restTodo) {
var deferred = $q.defer();
var successCb = function(resp) {
if(resp.responseStatus.errorCode) {
deferred.reject(resp.responseStatus.message);
} else {
deferred.resolve(resp);
}
};
$resource(restTodo).get({}, successCb);
return deferred.promise;
}
//now, problem is here in addTodo and clearCompleted functions,
//how do I call resolve to refresh my Todo List again?
function TodosListCtrl($scope, $resource, restTodo, todos) {
$scope.src = $resource(restTodo);
$scope.todos = todos;
$scope.totalTodos = ($scope.todos.result) ? $scope.todos.result.length : 0;
$scope.addTodo = function() {
$scope.src.save({ order: $scope.neworder,
content: $scope.newcontent,
done: false });
//successful callback, but how do I 'resolve' it?
};
$scope.clearCompleted = function () {
var arr = [];
_.each($scope.todos.result, function(todo) {
if(todo.done) arr.push(todo.id);
});
if (arr.length > 0) $scope.src.delete({ ids: arr });
//successful callback, but how do I 'resolve' it?
};
}