指令与不同模块的通信指令

时间:2014-09-14 10:33:19

标签: angularjs angularjs-directive

我试图找出如何在不同模块中的两个指令之间进行通信。如果它在同一模块中,我能够使它工作。请检查这里的小提琴。有人可以帮忙吗? http://jsfiddle.net/3wxy2m7m/1/

<body ng-app="MyApp">
  <basket apple orange>Roll over me and check the console!</basket>
</body>

var app = angular.module("MyApp", []);

app.directive("basket", function() {
  return {
    restrict: "E",
    controller: function($scope, $element, $attrs) {
      $scope.content = [];

      this.addApple = function() {
        $scope.content.push("apple");
      };

      this.addOrange = function() {
        $scope.content.push("orange");
      };
    },
    link: function(scope, element) {
      element.bind("mouseenter", function() {
        console.log(scope.content);
      });
    }
  };
});

app.directive("apple", function() {
  return {
    require: "basket",
    link: function(scope, element, attrs, basketCtrl) {
      basketCtrl.addApple();
    }
  };
});

var app2 = angular.module("MyApp2", ['MyApp']);
app2.directive("orange", function() {

  return {
    require: "basket",
    link: function(scope, element, attrs, basketCtrl) {
      basketCtrl.addOrange();
    }
  };
});

1 个答案:

答案 0 :(得分:0)

只需更改模块依赖项即可 从

var app = angular.module("MyApp", []);
var app2 = angular.module("MyApp2", ['MyApp']);

var app = angular.module("MyApp", ['MyApp2']);
var app2 = angular.module("MyApp2", []);