使用服务指令通信的指令

时间:2014-07-28 17:10:57

标签: angularjs

我正在尝试执行以下操作。使用一个指令设置服务中的信息。 使用另一个指令从此服务检索信息。设置信息的指令似乎正在做好它的工作,但接收信息的人不会对它做出反应。

以下是指令的外观:

app.service('theStore',function(){
  this.data;
});

app.directive('theOneThatSets', ['theStore', function(theStore){
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      element.click(function(event){
        theStore.data = attrs.val;
      });
    }
  };

}]);

app.directive('theOneThatReads', ['theStore', function(theStore){
  return {
    restrict: 'E',
    template: '<stong>Received Text is - {{receivedValue}}</strong>',
    link: function(scope, element, attrs) {
      scope.$watch('theStore.data',function(newVal){
        scope.receivedValue = theStore.data;
      });
    }
  };

}]);

plnkr:http://plnkr.co/edit/9EMIwhUcneQoopNqqWtV

1 个答案:

答案 0 :(得分:1)

我不知道你是否可以对不在范围内的事情做观察。在控制器/服务/指令之间进行通信的最佳方式是使用$ rootScope,$ broadcast和$ on。

使用您的代码的示例:

    app.directive('theOneThatSets', ['$rootScope', function(theStore){
      return {
        restrict: 'E',
        link: function(scope, element, attrs) {
          element.click(function(event){
            //theStore.data = attrs.val;
            $rootScope.$broadcast('changeThisValue', attrs.val); // Send
          });
        }
      };

    }]);

    app.directive('theOneThatReads', [function(theStore){
      return {
        restrict: 'E',
        template: '<stong>Received Text is - {{receivedValue}}</strong>',
        link: function(scope, element, attrs) {
          scope.$on('changeThisValue', function($event, value){
              scope.receivedValue = theStore.data;
          });
        }
      };
    }]);

另外,尝试在服务中创建一个监听器,如下所示:

    app.service('myservice',function(){
        this.listen = function($scope) {
            $scope.$watch(function(){return someScopeValue},function(){
               //$scope.dosomestuff();
            });
        }
    });

    //your controller

    function myCtrl($scope,myservice) {
        $scope.listen = function() {
            myservice.listen($scope);
        }

        //call your method
        $scope.listen();
    }