Angular JS — Call a Directive function in an outside Controller


I am newbie in Angular JS, so probably my issue is quite simple, but actually I haven’t found a solution for it.

I would like to know if it is possible to access a function (inside the link function in a directive) from an external controller. I am working with a Directive that control some variables required for the directive, and I need to access one of the from the controller. I was trying to create a function in the directive as:

scope.testArray = [{id=1, text="test1"},{id=2, text="test2"}];        
scope.getTestArray = function () {
return scope.testArray()

And from my controller I want to call it like this:

var testArray = scope.getTestArray()

But it says that the getTestArray does not exists for the element (scope). I assumed this is because the changes over the scope variable inside the directive, are not visible from the controller. So, Is there a way to achieve what I am trying to do?

Thanks for the help you can give me

Problem courtesy of: abottoni


You controller gets instantiated before the directive gets loaded. You can simply delay the call to the directive function by doing:

var testArray = $scope.getTestArray()

Or you dont need to wrap it in a function. Simply do this:

var testArray = $scope.testArray;

Solution courtesy of: AlwaysALearner

View additional discussion.