下面的代码仅仅是一个示例,因为我遇到的实际代码不是我可以共享的东西,我是新来的角,所以解决方案并不是非常明显,就像这样,我可以在几秒钟内使用jQuery。如何将消息从主模块发送到通知模块
在我的应用程序中,我有一个运行ajax的主模块,当ajax返回成功或失败时需要向通知模块发送消息。在示例代码中,您可以将所有模块更改为使用一个模块并且工作正常,第二次尝试使它作为两个模块工作,但不再工作,但不会引发JS错误。
对待ID的
theProcess
和
theMessage
作为两个单独的模块,假装theProcess是AJ ax调用服务器并返回字符串响应,然后将该字符串响应发送到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']);
working example using one module
你引导的2个模块seperately,所以你确实有在页面上2级不同的应用程序。尝试引导最低的模块(这是没有人依赖),在这种情况下,“notificationModule' –
@KobiCohen虽然你的评论是很难遵循没有一个例子它确实让我的东西,我能够解决这个问题,我会很快发布答案。 – Blindsyde