我有一个 Controller (如下)。我想从 $animate 的 .then() 方法中更新部分 newsCtrl。但是我无法访问它的变量。
正如您从代码中看到的,我的问题是当 currentPage 为“未定义”时
所以我想知道,如何从 .then() 方法中更新 currentPage?
AngularJS 文档建议我应该使用 $scope.$apply ( https://docs.angularjs.org/error/ $rootScope/inprog?p0=$apply)
但我没有在我的 Controller 上使用 $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 在他的 article about using Controller-As syntax 中举了一个例子.你的 promise 回调将变成类似
$animate.leave(myElem).then(angular.bind(this, function() {
this.currentPage === 0 // true
}));
promise 回调函数内部的 this 现在限定在 Controller 范围内。
关于javascript - 在 $animate .then() 方法中访问和更新 Controller 模型 - 使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29561701/