Sunday, December 10, 2017

AngularJs - Get Controller Scope in Directive

Recently I was learning AngularJs 5 and where I faced problem. I have to call controller function from directive. After struggle of half an hour, I was able to solve it. In this blog I am going to explain how to do this.

First of all give id to HTML tag where you have added ng-controller directive.

<div ng-controller="MyController" id="myControllerDiv">
</div>

Now in directive or any external JavaScript code where you want to get contoller scope, use following code.

var element  = document.getElementById("myControllerDiv");

This will give us that element, we will find it's corresponding angular element.

var angularElement  = angular.element(element);

Now we will get it's scope and using that scope, we can all any function of MyController

angularElement.scope().myFunction()

This will call myFunction defined in MyController.

Hope this helps you.

No comments:

Post a Comment