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

标签 javascript angularjs ajax

下面的代码只是一个示例,因为我遇到问题的实际代码不是我可以分享的,我是 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

working example using one module

最佳答案

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'

——科比·科恩

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

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

关于javascript - 如何从主模块向通知模块发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37845394/

相关文章:

javascript - 子组件中的 Vue Prop 未定义

javascript - 通过几个按钮滚动多个div的高度

angularjs - 使用下拉列表过滤数据?

javascript - 延迟js加载的最佳方法?

javascript - Chrome 应用中的 AJAX 请求有哪些限制?

javascript - Electron :总是返回 ontouchstart = true

javascript - 当使用 php 从 jquery 结果中单击一个时,在文本框中显示值

javascript - karma + Jasmine + JSONFixtures : Cannot read property 'ajax' of undefined

javascript - 在 AngularJS 中输入返回数字而不是字符串

mysql - 通过 AJAX 传递 dataURL