Accessing properties/methods defined under $rootScope from controllers in AngularJS


At one point or another, we often intend to share data between a controller and an application. Whenever we bootstrap our application in AngularJS using ng-app directive, it creates a root scope. Controllers also create their own scope when instantiated that prevent  us to access properties/methods defined in the root scope.  But we can obviate the problem by injecting the root scope into controllers using Dependency Injection.

In the following example, I’ve injected $rootScope into the controller to change the property btnVal defined inside myApp.run. Check out the working demo here.

If you are really looking out to share data between controllers then I would recommend to watch this video by simpulton explaining how to share data using a custom service in AngularJS. (Go through the top comment on youtube as well explaining another way to share data using $emit and $broadcast)

Advertisements

One thought on “Accessing properties/methods defined under $rootScope from controllers in AngularJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s