Search code examples
javascriptangularjsanimationangularjs-animation

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


I have a controller (below). I am wanting to update parts of newsCtrl from within the $animate's .then() method. But I am unable to access its variables.

As you can see from the code, my issue is when currentPage is "undefined"

So I am wondering, how can I update currentPage from within the .then() method?

AngularJS docs advise that I should use $scope.$apply (https://docs.angularjs.org/error/$rootScope/inprog?p0=$apply)

But I am not using $scope on my controller, I am using "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));

Solution

  • this inside of your promise success function is scoped differently than this outside of that function.

    To get around that issue, you can use angular.bind(). Todd Motto gives an example in his article about using Controller-As syntax. Your promise callback would then become something like

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

    this inside of the promise callback function is now scoped to the controller.