1

I have the following problem. I would like to call controller function from a directive with isolated scope.

HTML:

<div ng-controller="MainController">
   <test></test>
</div>

JS:

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

app.controller("MainController", function ($scope) {
    $scope.testFunction = function () {
        console.log("You just call testFunction()!");
    };
});

app.directive("test", function () {
    return {
        restrict: "E",
        scope: {},
        template: "<h1 ng-click='testFunction()'>Hello world!</h1>"
    };
});

When directive don't have an isolated scope, the call function follows.

Working DEMO

1 Answer 1

4

You can pass the function to be called using & like

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

app.controller("MainController", function($scope) {
  $scope.counter = 0;
  $scope.testFunction = function() {
    $scope.counter++;
  };
});

app.directive("test", function() {
  return {
    restrict: "E",
    scope: {
      myfn: '&myfn'
    },
    template: "<h1 ng-click='myfn()'>Hello world!</h1>"
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController">
  <test myfn="testFunction()"></test>
  <span>{{counter}}</span>
</div>

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.