Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 需要父控制器而不显式指定名称_Angularjs_Angularjs Directive - Fatal编程技术网

Angularjs 需要父控制器而不显式指定名称

Angularjs 需要父控制器而不显式指定名称,angularjs,angularjs-directive,Angularjs,Angularjs Directive,在子指令中需要父控制器的常见场景如下所示: 客户机指令需要父服务器控制器 <div server> <div client></div> </div> var app = angular.module("app", []); app.directive("server", function() { return { controller: function() { this.log = function

在子指令中需要父控制器的常见场景如下所示:

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

  <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也可以是“客户端”的父级



如果父控制器的类型可以是ServerMegaServer,如何定义我的Client指令以要求父控制器?

让另一台服务器在其
$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);
      };
    }
  };
});
试试看

  <div server>
    <div client></div>
  </div>
  <div mega-server>
    <div client></div>
  </div>
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);
      };
    }
  };
});