如何监视由服务操纵的范围变量的更改

时间:2014-11-15 19:30:45

标签: angularjs

我需要注意倒计时变量的变化,以便在时间结束时运行任务。 我正在使用服务来更新变量,正如您在此plunker中所看到的那样:

http://plnkr.co/edit/NJxqXcD2nhDKq4Q99Bgt

$scope.$watch('time', function (time) {
    // This portion of code is reached only twice:
    // Once when undefined and after first update.
    console.log(time);
});

我如何看待每项变更或从服务中触发我的任务(尽管我认为这是错误的选择)?

1 个答案:

答案 0 :(得分:1)

自从time引用未改变以来,Watcher仅触发两次。您有两个选择:打开对象相等(慢)或指定您自己的值提供者:

$scope.$watch('time', function () {
}, true); // Tells to check for object equality 

$scope.$watch(function () {
    return ($scope.time || {}).now;
}, function (now) {
    // magic
});

但我认为您应该考虑使用$timeout服务并承诺运行任务。

相关问题