我正在尝试更好地处理 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/