2016-06-15 65 views
1

下面的代码仅仅是一个示例,因为我遇到的实际代码不是我可以共享的东西,我是新来的角,所以解决方案并不是非常明显,就像这样,我可以在几秒钟内使用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']); 

2 Module FIDDLE

working example using one module

+1

你引导的2个模块seperately,所以你确实有在页面上2级不同的应用程序。尝试引导最低的模块(这是没有人依赖),在这种情况下,“notificationModule' –

+0

@KobiCohen虽然你的评论是很难遵循没有一个例子它确实让我的东西,我能够解决这个问题,我会很快发布答案。 – Blindsyde

回答

0

了Kobi科恩把我在正确的方向,我能够修复它,我把div的父母div标记包裹起来,然后给这个标签一个名为container的标识,然后我改变了我的bootstraps页面下方为阅读:

angular.bootstrap(document.getElementById('container'), ['masterModule', 'notificationModule']); 

See updated fiddle

相关问题