下面的代碼僅僅是一個示例,因爲我遇到的實際代碼不是我可以共享的東西,我是新來的角,所以解決方案並不是非常明顯,就像這樣,我可以在幾秒鐘內使用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