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

标签 javascript angularjs animation angularjs-animation

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

正如您从代码中看到的,我的问题是当 currentPage 为“未定义”时

所以我想知道,如何从 .t​​hen() 方法中更新 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/

相关文章:

javascript - jQuery/Javascript 将焦点传递给下一个元素,同时在页面中使用 tab 键

javascript - 使用 jquery 循环遍历列表项

ios - 选择选项在 IOS 中不适用于 ionic 1 应用程序

android - 使用 android 动画列表

WPF - 使动画的执行以绑定(bind)数据项的属性为条件

javascript - 周末、节假日计算在两个日期之间,无需迭代

javascript - 如何使用 CSS 为 JS 和 jQuery Scroller 修复侧边栏和标题

javascript - Jwplayer 与 angularjs

javascript - 如何在 Angular 元素中设置默认属性?

使用 <ul> 的 CSS3 循环动画