1

私はコントローラーを持っています(下)。$animate の .then() メソッド内から newsCtrl の一部を更新したいと考えています。しかし、その変数にアクセスできません。

コードからわかるように、私の問題は currentPage が「未定義」の場合です

それで、どうすれば .then() メソッド内から 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

thisthispromise 成功関数の内部は、その関数の外部とはスコープが異なります。

この問題を回避するには、 angular.bind()を使用できます。Todd Motto は、 Controller-As 構文の使用に関する記事で例を挙げています。あなたの約束のコールバックは、次のようになります

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

promise コールバック関数内の this は、コントローラーにスコープされるようになりました。

于 2015-04-10T14:04:01.360 に答える