如何从主模块向通知模块发送消息

时间:2016-06-15 20:42:15

标签: javascript angularjs ajax

下面的代码只是一个示例,因为我遇到问题的实际代码不是我可以分享的东西,我是角色的新手,所以解决方案不是很明显,像我这样的东西我可以用几个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

working example using one module

2 个答案:

答案 0 :(得分:0)

  

你单独引导2个模块,所以你实际上有2个   页面上的不同应用程序。尝试引导最低的   模块(没有人依赖),在本例中为“notificationModule”

- Kobi Cohen

https://docs.angularjs.org/guide/di

https://docs.angularjs.org/guide/module

答案 1 :(得分:0)

Kobi Cohen让我朝着正确的方向前进,我能够修复它,我将div包裹在父div标记中,然后为标记添加了一个名为{{1}的ID然后我改变了页面底部的引导程序,读作:

container

See updated fiddle