试图找出为什么当控制台告诉我一件事但是有角度的输出到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
答案 0 :(得分:3)
您需要使用$ 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();
}
答案 1 :(得分:1)
在呈现上下文后,您需要使用$scope
和$scope.$apply
来更新值。 tc
(this
)在控制器的生命周期中没有上下文。换句话说,你的tc赋值实际上只是函数本身。不是控制器的绑定上下文。
我有一个plnkr的分叉版本,有一个简单的例子可以让它工作。
http://plnkr.co/edit/fghSbSsarBbM0zv5EzoB?p=preview
$scope
和$apply
的文档可以在此处找到: