javascript - 变量在 Controller 中更新但未在 HTML 中更新?

标签 javascript angularjs settimeout angularjs-controller

我正在尝试更好地处理 Angular.js。 如标题中所述,我在 Controller 中有一个变量,当由成员函数调用时,该变量会更改值,但是更新不会推送到 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。有什么想法吗?

任何帮助将不胜感激。

最佳答案

将代码更改为这样应该可以:

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。

关于javascript - 变量在 Controller 中更新但未在 HTML 中更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25792898/

相关文章:

javascript - 通过单击按钮重定向到 jQuery 中的另一个网页

javascript - 使用 Flot 绘制事件持续时间图表

javascript - AngularJS:动态绑定(bind) Click in 指令被触发多次

angularjs - Jest 和混合 Angular/AngularJS 应用程序

javascript - 如何编写此 AngularJS 代码,单击时隐藏按钮,然后在 5 秒后显示它

reactjs - 使用axios限速的建议

javascript - setTimeout 和函数调用的调度

javascript - 无法将图像上传到 Node.js

javascript - Node v0.10.25 中的字符串原型(prototype)没有 'endsWith'

javascript - 使用 clearInterval() 时出错