2016-04-14 8 views
3

このコードを使用して、コントローラ、ディレクティブおよびサービス間でメッセージをパブリッシュおよびサブスクライブするファクトリを作成しています。AngularJSを使用してSubscribeサービスを公開

angular.module('app', []); 

angular.module('app').controller('TheCtrl', function($scope, NotifyingService) { 
    $scope.notifications = 0; 

    $scope.notify = function() { 
     NotifyingService.publish(); 
    }; 

    // ... stuff ... 
    NotifyingService.subscribe($scope, function somethingChanged() { 
     // Handle notification 
     $scope.notifications++; 
    }); 
}); 

angular.module('app').factory('NotifyingService', function($rootScope) { 
    return { 
     subscribe: function(scope, callback) { 
      var handler = $rootScope.$on('notifying-service-event', callback); 
      scope.$on('$destroy', handler); 
     }, 

     publish: function() { 
      $rootScope.$emit('notifying-service-event'); 
     } 
    }; 
}); 

それは正常に動作しているが、私は私はそれをどのように行うか、というの加入玉葉誰かに公開していながらデータを渡したいです。 4の値を公開するとします。これをどのように実行しますか?

答えて

0

私が正しく理解した場合、4'notifying-service-event'に公開し、その値をサブスクライバ内で使用したいとします。

値を公開するには、emit関数に値を渡す必要があります。

publish: function(msg) { 
      $rootScope.$emit('notifying-service-event', msg); 
     } 

次に、このパブリッシュ関数を使用しているときに、必要な値を渡します。

NotifyingService.subscribe($scope, function somethingChanged(event,msg) { 
     console.log(msg); //4 
     scope.number = msg //or whatever you want 
     scope.$apply(); 
    }); 

はあなたがここに完全な例を見つけることができます:

node.on("click", click); 

function click() { 
    NotifyingService.publish(4); 
} 

subscribeイベントを処理しながら Display informations about a bubble chart D3.js in AngularJS

:質問への答えをした

https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview

関連する問題