【问题标题】:How to watch service data in AngularJS?如何在 AngularJS 中查看服务数据?
【发布时间】:2014-03-17 18:22:15
【问题描述】:
myApp.directive('myView', ['myService',function($scope) {

  return {
    restrict    : 'C',
    template    : '',
    templateUrl : 'myView.html',
    controller  : function($scope,myService){
                    $scope.items = myService.$data;

                    $scope.$watch('myService.$data' , function(newVal, oldVal, scope) {
                     console.log("Watching items ...");
                    });
                  },

  };
}]);

我正在使用上面的代码,我想在其中观看 myService.$data ,它是在其服务中定义的。 $watch 在控制器加载时第一次被调用,在代码的其他地方我更新了服务变量 $data。当我使用 ng-repeat 指令并与 $data 绑定时,这会反映在 UI 中。
根据我在 UI 更新之前的理解,必须再次调用这个特定的手表,但事实并非如此。所以我假设我没有正确使用手表。

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    只要做:

    $scope.$watch(
        function() { return myService.$data; },
        function(...) { /*same*/ }
    );
    

    但是:

    如果$data 是一个对象,您可能需要将,true 添加到手表,这样即使内部属性发生更改,您也会收到通知:

    $scope.$watch(
        function() { return myService.$data; },
        function(...) { /*same*/ },
        true
    );
    

    您的代码中的声明是错误的。它应该是(仅显示更改):

    myApp.directive('myView', ['myService',function(myService) { // NOT $scope
        ...
        controller: ["$scope", function($scope) { // YOU GET myService FROM THE DIRECTIVE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多