Pracede
Pracede

Reputation: 4361

When and How to use broadcast event in Angularjs?

I am Angularjs but building a sample application. When i read some code, people broadcast event as :

 $rootScope.$broadcast('someevent');

For instance when login, many people use broadcast login success to notify to the whole application that the user is logged in. I knew that the logged in state can be managed using a $rootScope variable such as $rootScope.logged = true when authentication is in success or even by using AuthService which can be injected in controllers. The Authentication service will return the user with state and some user information.

My question are : 1- When and why to use $rootScope.$broadcast('someevent'); 2- What are drawbacks of maintaining the user authentication state using global varible or User Authentication Service ?

Thanks

Upvotes: 0

Views: 133

Answers (1)

Enzey
Enzey

Reputation: 5254

The draw back of placing any data or functions on $rootScope is that ALL child scopes also have that information, meaning you are polluting your scopes. If you are trying to share data between controllers and directives the best way to do so is to use a Service, Factory, or Provider.

Now I feel that using $broadcast from $rootScope is just fine as it is easier than $emiting and $broadcasting from your current scope to let the app know something really important occurred but just send the event, not the data. Then when a scope is interested in knowing about the data they should access it from the service.

If multiple controllers need to know that the login state changed then an event is the right way instead of them doing a $watch on the data from the service.

Upvotes: 1

Related Questions