AngularJS - 将事件从一个模块发送到另一个模块;它确实有效吗?

时间:2016-04-14 23:09:52

标签: javascript angularjs module

我需要一个解决方案,用于将事件从一个角度模块发送到另一个角度模块。 我在这里找到了这个线程,它解释了我想要的解决方案: How to send message from one module to another?Michael G.

但是,经过广泛的原型设计后,我不确定这是否真的有效。

简而言之,它显示了一个服务,其中包含两个方法:一个用于发送事件(由发送方调用),另一个用于接收方可以使用回调注册,该回调将在事件发生变化时触发。

任何人都可以提供一个有效的例子吗?

1 个答案:

答案 0 :(得分:0)

本作品:

HTML

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <m1></m1>
    <m2></m2>
  </body>

</html>

的JavaScript

angular.module('commoncore',[]).factory('NotifyService', function($rootScope) {
  return {
    onSomethingChanged: function(scope, callback) {
      var handler = $rootScope.$on('event:NotifyService.SomethingChanged', callback);
      scope.$on('$destroy', handler);
    },
    raiseSomethingChanged: function() {
      $rootScope.$emit('event:NotifyService.SomethingChanged');
    }
  };
});

angular.module('module1', ['commoncore']).directive('m1', [function() {
  return {
    restrict: 'E',
    template: '<div>{{vm1.name}}</div>',
    controllerAs: 'vm1',
    controller: ['$scope','NotifyService',function($scope,NotifyService) {
      this.name = 'm1';
      $scope.vm = this;
      NotifyService.onSomethingChanged($scope, function somethingChanged() {
        $scope.vm.name = 'm1 changed';
        console.log("M1 Changed");
      });
    }]
  }
}]);
angular.module('module2', ['commoncore']).directive('m2', [function() {
  return {
    restrict: 'E',
    template: '<div>{{vm2.name}} <button ng-click="vm2.DoSomething()">Change M1</button></div>',
    controllerAs: 'vm2',
    controller: ['NotifyService',function(NotifyService) {
      this.name = 'm2';
      this.DoSomething = function() {
        NotifyService.raiseSomethingChanged();
      };
    }]
  }
}]);

var app = angular.module('plunker', ['module1','module2']);


app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

演示:http://plnkr.co/edit/WDd8sKjJTlKpMvMCsizJ?p=preview

相关问题