我想从控制器(或服务)更新html值,但我不明白为什么$ watch不能正常工作。为什么当更新fn被称为$ watch时没有看到更改?
HTML:
<body ng-app="app">
<div ng-controller="BitWatch as bw">
<p>{{bw.watch.hours}}</p>
<p>{{bw.watch.mins}}</p>
<p>{{bw.watch.secs}}</p>
</div>
</body>
JS:
angular.module("app", [])
.controller("BitWatch", ["$scope", BitWatch])
.service("bitTime", bitTime);
function BitWatch($scope){
var self = this;
self.watch = new bitTime();
$scope.secs = self.watch.secs;
setInterval(function(){ self.watch.update(); $scope.secs = self.watch.secs; console.log(self.watch.secs, $scope.secs);}, 3000);
$scope.$watch( "secs", function(){ self.watch.update(); $scope.secs = self.watch.secs; console.log("chaged", self.watch.secs, $scope.secs); } );
}
function bitTime(){
var date = new Date();
var self = this;
var hours = date.getHours().toString(2);
self.hours = hours.length<4 ? "0000".substr(hours.length)+hours : hours;
var mins = date.getMinutes().toString(2);
self.mins = mins.length<6 ? "000000".substr(mins.length)+mins : mins;
var secs = date.getSeconds().toString(2);
self.secs = secs.length<6 ? "000000".substr(secs.length)+secs : secs;
self.update = function(){
var date_updated = new Date();
hours = date_updated.getHours().toString(2);
self.hours = hours.length<4 ? "0000".substr(hours.length)+hours : hours;
var mins = date_updated.getMinutes().toString(2);
self.mins = mins.length<6 ? "000000".substr(mins.length)+mins : mins;
var secs = date_updated.getSeconds().toString(2);
self.secs = secs.length<6 ? "000000".substr(secs.length)+secs : secs;
}
}
答案 0 :(得分:1)
因为使用setInterval时未应用对范围的更改。
请改用$interval
。 https://docs.angularjs.org/api/ng/service/ $间隔