1

Call a function on parent controller that is declared in is child directive.

Parent controller HTML

<div ng-click="testFunction()"></div>

Parent controller js

  $scope.testFunction = function(){
    $scope.functionFromChildDirective()
  }

Child directive js

function TestDirective() {

    return {
      restrict: 'EA',
      scope: {
      },  
      templateUrl: '',
      controller: function($scope) {
        "ngInject";

        $scope.functionFromChildDirective = function(){
          console.log("TEST")
        }

      }
    }
  }

  export default {
    name: 'testDirective',
    fn: TestDirective
  };
1
  • Attempting to call a function from a child component kind of goes against AngularJS' philosophy and the principle of separation of concerns. One cleaner and less tightly coupled approach would be using custom events. AngularJS Docs here Commented Jan 7, 2019 at 13:31

2 Answers 2

1

Just delete the empty scope deceleration, by defining it you are creating a new isolate scope. If you don't declare the scope in the directive definition object it will just inherit the parents scope. However with this approach the child directive can only be used once (i.e can't be repeated) as each instance of will just overwrite the $scope.functionFromChildDirective property.

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

1 Comment

Hello run, I need to have an isolated scope to pass another function from parent to child, I just deleted to simplify my question. There's no other way to do this? Thank you.
1

Use the ng-ref directive to bind the controller to a parent variable:

<test-directive ng-ref="testAPI">
</test-directive>
function TestDirective() {

    return {
      restrict: 'EA',
      scope: {
      },  
      templateUrl: '',
      controller: function() {
        this.testFn = function(){
          console.log("TEST")
        }

      }
    }
  }

To invoke it:

<div ng-click="testAPI.testFn()"></div>

The ngRef directive tells AngularJS to assign the controller of a component (or a directive) to the given property in the current scope.

For more information, see AngularJS ng-ref Directive API Reference.

1 Comment

Thanks for the help, I have not have the opportunity to test it yet, so I cannot accept as a correct answer, but I will do it soon. thanks for the help

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.