AngularJS - 绑定到提供程序属性

时间:2014-01-21 11:22:32

标签: angularjs angularjs-service

是否可以使用$ watch?

绑定serviceProvider中的日期

我的问题是我可以将提供商服务中的数据绑定到我的视图吗? 我尝试在我的视图中绑定$ get对象,因为提供程序是在init阶段加载的,没有控制器。

我试试这种方式,但我没有得到更新。 http://plnkr.co/edit/t3PrE6lX1EDIMuqKyTW0?p=preview

    <body ng-app="ServiceNotification">
    <div style="border-style:dotted" ng-controller="TimerCtrl1">
        TimerCtrl1<br/>
        Last Updated: {{lastUpdated}}<br/>
        Last Updated: {{calls}}<br/>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script type="text/javascript">
    var app = angular.module("ServiceNotification", []);

    function TimerCtrl1($scope, Timer) {
        $scope.$watch(function () { return Timer.data; }, function (data){
          console.log("In $watch - data:" + data);
          $scope.lastUpdated = data.lastUpdated;
          $scope.calls = data.calls;
       }, true); // <-- don't forgt the true
    };

    app.provider("Timer", function () {

      this.$get = function() {
        var data = { lastUpdated: new Date(), calls: 0 };

            var updateTimer = function () {
            data.lastUpdated = new Date();
            data.calls += 1;
            console.log("updateTimer: " + data.lastUpdated);

            window.setTimeout(updateTimer, 5000);
        };
        updateTimer();

        return {
            data: data
        }
      }
    });
</script>

谢谢托马斯

1 个答案:

答案 0 :(得分:0)

没有更新,因为setTimeout回调是在摘要周期之外调用的。角度(http://docs.angularjs.org/api/ng.$timeout)中有一个特殊的$timeout包装器,您可以将其注入$get提供程序方法。

app.provider("Timer", function () {  
  this.$get = function($timeout) {
    var data = { lastUpdated: new Date(), calls: 0 };

    var updateTimer = function () {
        data.lastUpdated = new Date();
        data.calls += 1;
        console.log("updateTimer: " + data.lastUpdated);
        $timeout(updateTimer, 5000);
    };
    updateTimer();

    return {
        data: data
    }
  }
});

演示:http://plnkr.co/edit/QUVuSnikIwVd3TocU7Vn?p=preview