变量在控制器中更新但未在HTML中更新?

时间:2014-09-11 16:45:46

标签: javascript angularjs settimeout angularjs-controller

我正在努力更好地处理Angular.js。 如标题中所述,我在控制器中有一个变量,当成员函数调用时会更改值,但更新不会推送到HTML。

这是我的代码:

HTML

<div class="row" id="copyMessage" ng-controller="swatchController as swatchCtrl" ng-    click="swatchCtrl.message()">
        <h1>{{swatchCtrl.inactive}}</h1> 
</div>

的JavaScript

app.controller('swatchController', function(){
    this.inactive = true; //This is the variable whose value I want to change

    this.message = function(){ //This function is called in my HTML 
        this.inactive = false; 
        setTimeout(function(){
            this.inactive = true;
            alert(this.inactive); //Spits out true as expected but this value is not pushed to HTML
        }, 2000);           
    };
});

同样,这里的问题是即使在onclick上调用了message()函数之后,swatchCtrl.inactive仍然为false。有什么想法吗?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

将代码更改为此应该有效:

app.controller('swatchController', function($timeout){
    var _this = this;

    this.inactive = true; //This is the variable whose value I want to change

    this.message = function(){ //This function is called in my HTML 
        this.inactive = false; 
        $timeout(function(){
            _this.inactive = true;
            alert(_this.inactive); //Spits out true as expected but this value is not pushed to HTML
        }, 2000);           
    };
});

你不能在超时回调中使用this键盘,因为它引用了其他内容。您还应该使用Angular的$timeout而不是setTimeout,以便Angular知道在完成时更新DOM。

答案 1 :(得分:1)

这是this在Javascript中的工作原理。改为改为:

app.controller('swatchController', function($timeout){
    var self = this;

    this.inactive = true; //This is the variable whose value I want to change

    this.message = function(){ //This function is called in my HTML 
        this.inactive = false; 
        $timeout(function(){
            self.inactive = true;
            alert(self.inactive); //Spits out true as expected but this value is not pushed to HTML
        }, 2000);           
    };
});

this的值在Javascript中会发生变化,具体取决于执行上下文,因此在您的示例中,this中的timeout不再代表控制器,而是指代全球范围(Window)。

在控制器加载时使用闭包并保存对this的引用是您解决此问题的方法。