1

我有一个控制器(下)。我想从 $animate 的 .then() 方法中更新 newsCtrl 的一部分。但我无法访问它的变量。

从代码中可以看出,我的问题是 currentPage 是“未定义”时

所以我想知道,如何从 .t​​hen() 方法中更新 currentPage ?

AngularJS 文档建议我应该使用 $scope.$apply ( https://docs.angularjs.org/error/ $rootScope/inprog?p0=$apply)

但我没有在我的控制器上使用 $scope,我使用的是“this”。

(function(angular, $) {

    angular.module('app-news', ['ngAnimate']);

    function newsCtrl($animate) {
        this.currentPage = 0;

        this.cycleNews = function(bool) {

            // this.currentPage = 0

            $animate.leave(myElem).then(function() {
                // this.currentPage = undefined
                // $scope.currentPage = undefined
                // newsCtrl.currentPage = undefined
                $scope.$apply(function(){
                    // this.currentPage = undefined
                    // $scope.currentPage = undefined
                    // newsCtrl.currentPage = undefined
                });
            });
        }
    }

    angular
        .module('app-news')
        .controller('newsCtrl', ['$animate', newsCtrl]);

}(window.angular, window.jQuery));
4

2 回答 2

2

this您的承诺成功功能内部的范围与该功能之外的范围不同this

要解决该问题,您可以使用angular.bind()。Todd Motto 在他的文章中给出了一个关于使用 Controller-As 语法的例子。你的承诺回调会变成类似

$animate.leave(myElem).then(angular.bind(this, function() {
    this.currentPage === 0 // true 
}));

承诺回调函数内部的 this 现在作用于控制器。

于 2015-04-10T14:04:01.360 回答
2

成功的承诺的this内在并不是this你想象的那样。

您需要分配this给函数内部的某些内容cycleNews(),例如self = this;,然后self在承诺解决方案中引用而不是this

于 2015-04-10T14:07:41.350 回答