2016-04-14 4 views
0

ある角度モジュールから別の角度モジュールにイベントを送信するソリューションが必要です。しかし、大規模なプロトタイピングの後、私はこれが実際に動作するかわからない How to send message from one module to another?AngularJS - あるモジュールから別のモジュールにイベントを送信する。それは本当に機能しますか?

Michael G.によって: 私はそれをしたいと思いますどのように正確に解決策を説明し、ここでこのスレッドを発見しました。

簡単に言えば、イベントを送信する(送信者によって呼び出される)方法と、受信者がイベントの変更時にトリガされるコールバックに登録できる方法の2つの方法を含むサービスを示します。

実例は誰でも提供できますか?

答えて

0

この作品:

HTML

<!DOCTYPE html> 
<html ng-app="plunker"> 

    <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script> 
    <script src="app.js"></script> 
    </head> 

    <body ng-controller="MainCtrl"> 
    <p>Hello {{name}}!</p> 
    <m1></m1> 
    <m2></m2> 
    </body> 

</html> 

はJavaScript

angular.module('commoncore',[]).factory('NotifyService', function($rootScope) { 
    return { 
    onSomethingChanged: function(scope, callback) { 
     var handler = $rootScope.$on('event:NotifyService.SomethingChanged', callback); 
     scope.$on('$destroy', handler); 
    }, 
    raiseSomethingChanged: function() { 
     $rootScope.$emit('event:NotifyService.SomethingChanged'); 
    } 
    }; 
}); 

angular.module('module1', ['commoncore']).directive('m1', [function() { 
    return { 
    restrict: 'E', 
    template: '<div>{{vm1.name}}</div>', 
    controllerAs: 'vm1', 
    controller: ['$scope','NotifyService',function($scope,NotifyService) { 
     this.name = 'm1'; 
     $scope.vm = this; 
     NotifyService.onSomethingChanged($scope, function somethingChanged() { 
     $scope.vm.name = 'm1 changed'; 
     console.log("M1 Changed"); 
     }); 
    }] 
    } 
}]); 
angular.module('module2', ['commoncore']).directive('m2', [function() { 
    return { 
    restrict: 'E', 
    template: '<div>{{vm2.name}} <button ng-click="vm2.DoSomething()">Change M1</button></div>', 
    controllerAs: 'vm2', 
    controller: ['NotifyService',function(NotifyService) { 
     this.name = 'm2'; 
     this.DoSomething = function() { 
     NotifyService.raiseSomethingChanged(); 
     }; 
    }] 
    } 
}]); 

var app = angular.module('plunker', ['module1','module2']); 


app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
}); 

デモ:http://plnkr.co/edit/WDd8sKjJTlKpMvMCsizJ?p=preview

+0

これは、優れた作品が、それは2つの他のモジュールを注入する一つのアプリケーションです。私はより分離されたアプローチを望んでいます:2つのモジュールは、プランナーモジュールを注入... それは可能ですか?スコープ/ルートスコープを共有できますか? –

+0

@ R.Pieterse私はこの点を得ることができません "プランカモジュールを注入する2つのモジュール...可能ですか?" – sreeramu

+0

私の悪い、私はcommoncoreモジュールを意味した。 :-S 私の最初の質問の例で説明したように、イベントの「送信者」と「受信者」の両方にcommoncoreサービスを注入したいと思います。 実際には自分のアプリは「受信者」ですが、「送信者」とcommoncoreサービスは不幸にも制御できません。 したがって、私はcommoncoreサービスが他のモジュールについて無関係であることを望みます。 –

関連する問題