下面的代码只是一个示例,因为我遇到问题的实际代码不是我可以分享的,我是 Angular 的新手,所以解决方案不是非常明显,我可以在一些情况下使用 jQuery 来完成类似的事情秒。
在我的应用程序中,我有一个运行ajax的主模块,当ajax返回成功或失败时,它需要向通知模块发送消息。在示例代码中,您可以将所有模块更改为使用一个模块,并且它工作正常,第二次我尝试将其作为两个模块工作时,它不再工作,但不会引发 JS 错误。
处理 ID
theProcess
和
theMessage
作为两个独立的模块,假设theProcess是对服务器进行的ajax调用并返回字符串响应,然后将该字符串响应发送到theMessage模块.
请参阅下面的代码。
HTML:
<div id="theProcess" ng-controller="ControllerZero">
<input ng-model="message">
<button ng-click="handleClick(message);">LOG</button>
</div>
<div id="theMessage">
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
</div>
JS:
var masterModule = angular.module('masterModule', []);
masterModule.controller('ControllerZero', ['$scope', function($scope) {
$scope.handleClick = function(msg) {
$scope.$emit('handleEmit', {
message: msg
});
};
}]);
var notificationModule = angular.module('notificationModule', ['masterModule']);
notificationModule.run(function($rootScope) {
$rootScope.$on('handleEmit', function(event, args) {
$rootScope.$broadcast('handleBroadcast', args);
});
});
notificationModule.controller('ControllerOne', ['$scope', function($scope) {
$scope.$on('handleBroadcast', function(event, args) {
$scope.message = 'ONE: ' + args.message;
});
}]);
notificationModule.controller('ControllerTwo', ['$scope', function($scope) {
$scope.$on('handleBroadcast', function(event, args) {
$scope.message = 'TWO: ' + args.message;
});
}]);
angular.bootstrap(document.getElementById('theProcess'), ['masterModule']);
angular.bootstrap(document.getElementById('theMessage'), ['notificationModule']);
<强> 2 Module FIDDLE
最佳答案
You bootstrap the 2 modules seperately, so you actually have 2 different applications on the page. try to bootstrap the lower most module (which no one is depend on), in this case "notificationModule'
——科比·科恩
关于javascript - 如何从主模块向通知模块发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37845394/