【发布时间】: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