3

The common scenario of requiring a parent controller in a child directive shown here:

the Client directive requires the parent Server controller

  <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!");
    }
  };
});

What if I have a third directive directive called MegaServer

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

MegaServer can also be a parent to "Client".

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

How do I define my Client directive to require the parent controller if it can be of type either Server or MegaServer?

0

1 Answer 1

2

Have the other server publish its this on its $scope. Then have the client directive use either the optionally required serverCtrl or the $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);
      };
    }
  };
});

Try it out on JSFiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.