Sunday, October 25, 2015

Pitfall in access AngularJS function from non-angular environment

In Google you will find lot of answer but there is one pitfall which I realize from my personal practical experience.

Suppose, we want to access AngularJS function from non-Angular environment (like JQuery and other JS environment). How we can do that? Very simple.

  angular.element(document.getElementById(‘Id')).scope().YourFunction();
     
Yes, we are getting element by Id and in this article here I want to focus. If you think that the “Id” is any Id value from DOM then you are wrong.

To make it work, please use the element Id where your controller is defines. Here is the example.

<div id='myId' ng-controller="IndexPageController">

In this <div> we are specifying the controller and once we want to access the function use “myId” in syntax. So the syntax will be like this.

angular.element(document.getElementById(‘myId')).scope().YourFunction();

Otherwise you may encounter function not found error. 


No comments:

Post a Comment