【发布时间】:2015-02-27 12:26:54
【问题描述】:
我想知道我们能否在 AngularJS 中的两个不同控制器之间进行通信。假设我有两个模块,
笨蛋: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', ['$scope',
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>
【问题讨论】:
-
无论它们是否在同一个模块中都不会改变任何东西。
-
这意味着我可以使用 $broadcast 在控制器之间进行通信。
-
是的,这样做没问题。
-
@JBNizet 你可以为此创建一个示例。请..
-
你这样做怎么样,如果你不成功就问一个问题?
标签: angularjs