この作品:
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
これは、優れた作品が、それは2つの他のモジュールを注入する一つのアプリケーションです。私はより分離されたアプローチを望んでいます:2つのモジュールは、プランナーモジュールを注入... それは可能ですか?スコープ/ルートスコープを共有できますか? –
@ R.Pieterse私はこの点を得ることができません "プランカモジュールを注入する2つのモジュール...可能ですか?" – sreeramu
私の悪い、私はcommoncoreモジュールを意味した。 :-S 私の最初の質問の例で説明したように、イベントの「送信者」と「受信者」の両方にcommoncoreサービスを注入したいと思います。 実際には自分のアプリは「受信者」ですが、「送信者」とcommoncoreサービスは不幸にも制御できません。 したがって、私はcommoncoreサービスが他のモジュールについて無関係であることを望みます。 –