javascript - AngularJS 解析 Promise

标签 javascript angularjs

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

然后我意识到一个问题,该示例仅向我展示了如何在我第一次访问此路由时解析 GET 调用以获取待办事项列表。

但是,在同一路径的同一页面中,我有一个添加按钮来发布新的待办事项,还有一个清除按钮来删除已完成的项目。

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

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

enter image description here

主要.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?
    };   
}

最佳答案

我认为您忽略了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() .

关于javascript - AngularJS 解析 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13379222/

相关文章:

javascript - 在 Angular 1.5 中为 ng-pattern 生成正则表达式

javascript - 我在一个 Controller 上获得了一个数据(来自服务器的 token ),并且想在 Angular js 的另一个 Controller 中使用该数据( token )?

javascript - 如何计算数组中的某些元素?

php - 在 php 中,如何获取 XMLHttpRequest 的 send() 方法的文本/纯文本值

javascript - 如何添加链接切换图片?

javascript - 可以在一个文件中加载多个 Google 脚本

javascript - AngularJs 模板 url 加载抛出 CORS 错误

javascript - 用于动态创建组件的 React v4 路由

javascript - 使用分页 AngularJs 进行复合过滤

javascript - 指令的竞争条件