Angularjs 角坐标中的摘要环
为什么即使Angularjs 角坐标中的摘要环,angularjs,Angularjs,为什么即使now变量已更改,也不会触发以下代码的摘要循环 var app = angular.module('coolName',['ngResource']); app.controller('TimeController', function($scope) { $scope.now = new Date().toLocaleTimeString(); setInterval(function() { $scope.now = new Date().toLocaleTimeStrin
now
变量已更改,也不会触发以下代码的摘要循环
var app = angular.module('coolName',['ngResource']);
app.controller('TimeController', function($scope) {
$scope.now = new Date().toLocaleTimeString();
setInterval(function() {
$scope.now = new Date().toLocaleTimeString();
console.log($scope.now);
}, 1000);
});
使用
$interval
代替setInterval
:
app.controller('TimeController', function($scope, $interval) {
$interval(function() {
$scope.now = new Date().toLocaleTimeString();
console.log($scope.now);
}, 1000);
});
setInterval
不是角度构造,因此不会触发摘要循环。但是,$interval
是,因此它会触发循环。您将无法在setInterval
中访问$scope
,但您可以通过以下方式访问作用域:
var $myscope = angular.element([Some DOMElement]).scope();
然后调用后面跟有$digest()
的相同代码:
$myscope.now = new Date().toLocaleTimeString();
$myscope.$digest(); // this will refresh the UI