在 $animate .then() 方法中访问和更新控制器模型 - 使用 'this'

Accessing and updating controller model within $animate .then() method - using 'this'

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

正如您从代码中看到的,我的问题是当 currentPage 是 "undefined"

所以我想知道如何从 .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));

this 在您的 promise success 函数内部的作用域与 this 在该函数外部的作用域不同。

要解决该问题,您可以使用 angular.bind(). Todd Motto gives an example in his article about using Controller-As syntax。你的 promise 回调会变成类似

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

promise 回调函数的内部现在限定在控制器范围内。

successful promise里面的this并不是你想的this

您需要将 this 分配给 cycleNews() 函数中的某些内容,例如self = this; 然后在 promise 决议中引用 self 而不是 this