AngularJS解决承诺

时间:2012-11-14 12:54:40

标签: javascript angularjs

我正在学习如何使用an example中的解析,并将其应用到我的Todo脚本中。

然后我意识到一个问题,这个例子只是向我展示了当我第一次访问这条路线时如何解决GET调用以获取Todo List。

然而,在同一路线的同一页面上,我有一个添加按钮来POST新待办事项,也有一个清除按钮来删除已完成的项目。

查看我的$scope.addTodo = function() {$scope.clearCompleted = function () {我希望在操作后再次解析我的TodoList。我怎么能这样做?

这是我的代码。在我的代码中,初始resolve: { todos: TodosListResl }正在运行,它会命中TodosListResl函数并产生承诺。但是,当我想要再次解析待办事项列表时,我不知道如何处理addTodoclearComplete

enter image description here

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?
    };   
}

1 个答案:

答案 0 :(得分:3)

我认为你错过了resolve的观点。 resolve的要点是“delay route change until data is loaded。在您的情况下,您已经在路线上了,并且您希望保持该路线。但是,您想要更新todos变量成功回调。在这种情况下,您不想使用resolve。而是只需要做需要做的事情。例如

$scope.addTodo = function() {
    $scope.src.save({ order: $scope.neworder, 
                      content: $scope.newcontent, 
                      done: false }, function () {
        todos.push({ order: $scope.neworder, 
                      content: $scope.newcontent, 
                      done: false });
    }); 
                    //successful callback, but how do I 'resolve' it?
};

作为一个侧面点,我注意到你最有可能使用来自Underscore库的_。您不需要使用其他库,因为Angular已经有$angular.forEach()