【问题标题】:Variable updated in controller but not updated in HTML?变量在控制器中更新但未在 HTML 中更新?
【发布时间】:2014-09-11 16:45:46
【问题描述】:

我正在尝试更好地处理 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。有什么想法吗?

任何帮助将不胜感激。

【问题讨论】:

  • 使用$timeout 以便回调启动一个摘要循环。还要检查 this 在所有实例中是否引用了控制器。
  • 我会将$scope 注入控制器并使用$scope 而不是this (在您的代码中,setTimeout 中的this 不是您所期望的)。此外,通常建议不要使用setTimeout,而是使用$timeout(你也需要注入)

标签: javascript angularjs settimeout angularjs-controller


【解决方案1】:

将您的代码更改为此应该可以:

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。

【讨论】:

  • 使用 $timeout 和 _this 就可以了。感谢您的帮助!
【解决方案2】:

这是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 中根据执行上下文而变化,因此在您的示例中,timeout 内的 this 不再代表控制器,而是指全局范围(@987654326 @)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多