我想知道我们可以在AngularJS中的两个不同控制器之间进行通信.假设我有两个模块,
Plunker: http://plnkr.co/edit/if0MQwlx9WHrD8XnMi2t?p=preview
Plunker: http://plnkr.co/edit/if0MQwlx9WHrD8XnMi2t?p=preview
1. var app = angular.module('fistModule',[]); app.controller('first',function ($scope) { $scope.firstMethod= function () { //my code} } ) 2. var newapp = angular.module('secondModule,[]'); newapp.controller('second',function ($scope) { $scope.secondMethod= function () { //my code}
有没有办法在两个不同模块的控制器之间进行通信.
我的代码:
JS:
angular.module('myApp',[]) .controller('ParentCtrl',['$scope',function($scope) { $scope.message = "Child updated from parent controller"; $scope.clickFunction = function() { $scope.$broadcast('update_parent_controller',$scope.message); }; } ]); angular.module('myNewApp',[]) .controller('ChildCtrl',function($scope) { $scope.message = "Some text in child controller"; $scope.$on("update_parent_controller",function(event,message) { $scope.message = message; }); } ])
HTML:
<div ng-app="myApp" ng-controller="ParentCtrl"> <div ng-app="myNewApp" ng-controller="ChildCtrl"> <p>{{message}}</p> </div> <button ng-click="clickFunction()">Click</button> </div>
正如@JB Nizet所说,你这样做的方式完全相同.您使用服务在两个控制器之间进行通信.
一个模块需要将另一个模块作为依赖项.这始终是单向依赖.我已经使secondModule成为firstModule的依赖项.
同样,服务中的值存储在一个名为data的对象中.这是因为JavaScript不通过引用传递值 – 而是通过引用传递对象.所以这是一种拳击形式.
angular.module('firstModule',['secondModule']) .controller('FirstController',FirstController) .service('sharedData',SharedData); FirstController.$inject = ['sharedData']; function FirstController(sharedData) { this.data = sharedData.data; } function SharedData() { this.data = { value: 'default value' } } angular.module('secondModule',[]) .controller('SecondController',SecondController); SecondController.$inject = ['sharedData']; function SecondController(sharedData) { this.data = sharedData.data; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="firstModule"> <div ng-controller="FirstController as vm"> First Controller in module firstModule<br> <input type=text ng-model="vm.data.value" /> </div> <div ng-controller="SecondController as vm"> Second Controller in module secondModule<br> {{vm.data.value}} </div> </div>