Reputation: 543
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));
Upvotes: 1
Views: 142
Reputation: 6973
The this
inside the successful promise isn't the this
that you think it is.
You need to assign this
to something inside your cycleNews()
function, e.g. self = this;
and then refer to self
in the promise resolution instead of this
Upvotes: 1
Reputation: 179
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.
Upvotes: 1