0
votes

I have 2 directives, <parent-directive> and <child-directive>. <parent-directive> has its controller called "parentCtrl" and <child-directive> has its controller called "childCtrl"

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

    myApp.directive("parentDirective", function() {
      return {
        restrict: "E",
        templateUrl: "parent.html",
        controller: [
          "$scope",
          function($scope) {
            var self = this;
        
            var parentSayHello = function(){
              console.log("Hello from parent");
            };


            var callChildSayHello = function(){
              // want to call the say hello method defined in childCtrl here
              // ...
            };

          }
        ],
        controllerAs: "parentCtrl"
      };
    });

myApp.directive("childDirective", function() {
      return {
        restrict: "E",
        templateUrl: "child.html",
        controller: [
          "$scope",
          function($scope) {
            var self = this;
        
            var childSayHello = function(){
              console.log("Hello from child");
            };

            var callParentSayHello = function(){
              // want to call the say hello method defined in parentCtrl here
              // ...
            };


          }
        ],
        controllerAs: "childCtrl"
      };
    });

In html, parentDirective and childDirective are nested directives:

    <parent-directive>
          <child-directive></child-directive>
    </parent-directive>



How could parent directive's controller call a method from child directive's controller and vice versa? (i.e., how to implement callChildSayHello & callParentSayHello as shown in the JS code above)

1
You can use service to do it. BTW, why you use directive instead of component? It should be easier for you to migrate to new NG later.huan feng

1 Answers

0
votes

From doc, Best Practice is to use controller when you want to expose an API to other directives.

Detail examples could be found in the link.

You can also call parent (directive/component) method in child directive via '&' function input:

JS:

angular.module('yourModule').directive('childDirective', [function () {
    'use strict';
    return {
        restrict: 'EA',
        scope: {
            callback: '&'
        },
        templateUrl: 'xxx.html'
    };
}]);

HTML:

<child-directive callback="methdoInParentDirective()"></child-directive>