![](/img/trans.png)
[英]$scope variable inside the function is not getting updated in angular js
[英]Angular - why is the scope not updated inside of this function
试图弄清楚为什么控制台告诉我一件事,而angular向html的输出却告诉我另一件事。
码
angular.module('global',[]);
angular.module('global').controller('thisTestController', thisTestController);
function thisTestController() {
var tc = this;
tc.status = "not loaded";
function activate() {
var background = new Image();
background.onload = function () {
tc.status = "loaded";
console.log(tc.status);
};
background.src = 'http://placehold.it/350x150';
}
activate();
}
HTML
<body ng-app="global">
<div ng-controller="thisTestController as tc">Status = {{tc.status}}</div>
</body>
结果
Console.log - loaded
HTML - Status = not loaded
您需要使用$ scope绑定控制器,如下所示: http : //plnkr.co/edit/CV7rgBGQMnRlNDnYSQIq?p=preview
angular.module('global', []);
angular.module('global').controller('thisTestController', thisTestController);
function thisTestController($scope) {
var tc = this;
tc.status = "not loaded";
function activate() {
var background = new Image();
background.onload = function() {
tc.status = "loaded";
$scope.$apply();
console.log(tc.status);
};
background.src = 'http://placehold.it/350x150';
}
activate();
}
渲染上下文后,需要使用$scope
和$scope.$apply
更新值。 tc
( this
)在控制器的生命周期中没有上下文。 换句话说,您的tc分配实际上只是函数本身。 不是控制器的绑定上下文。
我有您的plnkr的分叉版本,并提供了一个简单的示例来使其正常运行。
http://plnkr.co/edit/fghSbSsarBbM0zv5EzoB?p=preview
$scope
和$apply
文档可在以下位置找到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.