angular require父控制器没有明确指定名称

时间:2015-11-15 14:43:29

标签: angularjs angularjs-directive

在此处显示的子指令中需要父控制器的常见情况:

客户端指令需要父服务器控制器

  <div server>
    <div client></div>
  </div>



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

app.directive("server", function() {
  return {
   controller: function() {
      this.log = function(message) {
        console.log(message);
      };
    }
  };
});

app.directive("client", function() {
  return {
    require: "^server",
    link: function($scope, $elem, $attrs, serverCtrl) {
      serverCtrl.log("Hello, this is the client!");
    }
  };
});

如果我有第三个指令指令 MegaServer

,该怎么办?
app.directive("MegaServer", function() {
  return {
   controller: function() {
      this.log = function(message) {
        console.log(message);
      };
    }
  };
});

MegaServer 也可以是&#34;客户&#34;的父母。

  <div server>
    <div client></div>
  </div>
  <div mega-server>
    <div client></div>
  </div>

如何定义客户端指令以要求父控制器,如果它可以是服务器 MegaServer 的类型?

1 个答案:

答案 0 :(得分:1)

让其他服务器在其this上发布其$scope。然后让client指令使用可选的serverCtrl$scope.serverCtrl

angular.module("app").directive("otherServer", function() {
  return {
   controller: function($scope) {
      $scope.serverCtrl = this;       
      this.log = function(message) {
        console.log("otherServer: ", message);
      };
    }
  };
});

angular.module("app").directive("client", function() {
  return {
    require: "^?server",
    link: function(scope, elem, attrs, serverCtrl) {
      var ctrl = serverCtrl || scope.serverCtrl;
      if (ctrl) {  
         ctrl.log("Hello, from a client");
         ctrl.log("My scope.$id is " + scope.$id);
      };
    }
  };
});

尝试on JSFiddle