Monday, June 23, 2014

How to Access $scope Variable Outside AngularJs Controller

Recently I was working with AngularJs and there was a requirement to call a AngularJs controller function forcefully from other events.  So for that we have to access $scope variable of a controller. This short blog is about accessing $scope variable.

In AngularJs all the scopes are bound to DOM so to access $scope first we have to get the HTML element. You can either use jQuery selectors to get elements or you can use standard document.getElementById method. For example.

var scope= angular.element($(".classselector")[0]).scope();

This gives you the scope of the the element. Once you have the scope you can call respective method of controller.  There is also other way to find out the scope if you don't have reference to element. You can find scope by name of controller.

var scope = angular.element($('[ng-controller=myController]')).scope();

After you make changes to variables of scope you have to call apply method so the AngularJs framework is notified about changes.


Hope this helps you.

No comments:

Post a Comment