Is it normal to use $broadcast in angularjs? - angularjs

I have a search controller, where the user can search for a single area.
After an area is searched, I $rootScope.$broadcast that the area has changed.
I have various other controllers that are responsible for independently loading and showing data about that area. They use $rootScope.$on, and get extra information from other sources using $http.
Is my approach the normal way of doing things? It feels unusual, since $broadcast wasn't mentioned in the tutorials I have been through.
I am trying to learn angular.

$emit/$broadcast are used a lot in angular libraries and even 3rd parties.
For instance you have events when navigating using the ng-route module, $routeChangeStart, $routeChangeSuccess, ... same goes for the 3rd party ui-router : $stateChangeStart, $stateChangeSuccess,....
It's just an event bus : listening and sending events in order to communicate with external components.
In angularJS, you will find them in the event part of the documentation.
However you should be carefull with events, too many of them can lead to lost control of what you're code is doing or be able to tell what should be the current state of your app.
It's possible for some that a cleaner way of doing it is tostore data in $rootScope/a service an use $watch on them.
EDIT : i didn't mention it but storing data in $rootScope is not advised for design/reusability.isoltion purpose.

Related

how to share data between two controllers without using service and rootscope?

i have faced this question in an interview, i know how to share data between two controllers using service and also using root scope. Is there any way to do with in angular to pass data between two controllers without using service and root scope>
Any suggestions please.
AngularJs uses the Observer pattern which consists on sending and reading events.
There are many times when one part of the application changes, other parts needs to be updated. In AngularJS, if the $scope object updates, an event can be triggered to notify another component. The observer pattern incorporates just that - if an object is modified it broadcasts to dependent objects that a change has occurred.
In short:
$scope.$emit() OR $scope.$broadcast() depending on your position and what is your 'reader'
Then
$scope.$on()
The best practice states using a service, you could also use $rootScope by assigning object literal $rootScope.sharedVar. There's also a $broadcast method, which is an observer pattern, works like pub/sub.
The least recommended way would be leveraging your $parent scope and drilling down your element (depending where it's located in the DOM tree)

AngularJs controller and directive purpose, the right way?

I've been reading up a more in depth about angularjs directive and controller, what should be in one and the other. The situation is this, I have multiple people with their types -> policemen, medicine, lawyers ... etc. inside the admin panel app, where the admin can manage them. In one section the admin can create, edit, delete them. The current versions controller does almost all the work: UI (bringing up the right form, hiding the other forms...), and logic (deleting, creating, updating methods for each person type). As I understand this is not good, because the controller does multiple things (no single responsibility). And even further the controller should only bind values to scope.
But does that mean, that I should only pull all the people (inside controller) and pass it some master directive which will manage it all? Or should their be more directives inside directives to divide the responsibility?
And if so, the controller will have to use the same service as the directive/directives. Controller for pulling people from back-end) and the directive/directives (for creating/updating/deleting) is this DRY?
Without code it's hard to give a precise answer, but the general idea when working with angular is this:
Controller: The controller is responsible for keeping the views up to date with all the changes that are happening throughout your app. This means that it should not contain the business logic, this logic should instead be separated into small services. Each handling different parts of the logic for your app.
Service: As stated above, a service should contain your business logic. Meaning that heavy calculations, manipulations etc. should be put into a service. Since services are singletons you can easily inject this service anywhere and re-use the logic within it, something you cannot do if you've put your logic inside a controller.
Directives: Like controllers, directives shouldn't have any business logic in them. Directives are only there to create re-useable functionality as well as giving you a place to handle direct DOM changes. DOM changes should never be done anywhere but from within a directive.
To answer this:
And if so, the controller will have to use the same service as the directive/directives. Controller for pulling people from back-end) and the directive/directives (for creating/updating/deleting) is this DRY?
If you have the data bound to a controller, you should not necessarily need a directive to handle the CRUD operations. Since the data is bound to the controller, you can easily create a template which reacts to the data changes automatically using ng-repeat, ng-if and so on.

How to turn off eventListeners for inactive views in Ionic

Within many views I am listening to keyboard events. I would like to limit listening to only currently active state. I have tried using ionic.EventController.on and ionic.on but they seem to be just a thin wrapper around classic eventListener. I have also tried listening for the events on ion-view tag but it seems that they are only send to the window object.
I am aware that I can workaround usting active/inactive flag for each controller I care about but I would like to know if there is ionic or angular specific mechanism for that.
For people not familiar with Ionic, views are cached so $scopes are not destroyed.
Thanks in advance

What is the preferred way to make different parts of an angularjs app talk to each other?

I was wondering what is the preferred way to make different part of an app interact with each other.
For instance let's say we have a directive A that display a product in the shopping basket of a user. This directive has access to a persistence service that allows CRUD operations on the item.
Let's also say we have a directive B that displays a general message.
Now the user decides to delete a product from his basket. Is it acceptable to make it publish an event this way?:
$scope.$emit("item-deleted");
and then have B listening on that type of event:
$scope.$on("data-received", function(event, next, current) {
// show up and tell "item deleted succesfully"
});
Is it a good way to achieve the result? It definitely is in other frameworks and in UI development in general. I was just wondring if it is a viable way in angular.
Thanks
You should use services instead of events propagation. With the dependency injection, it is really easy to use. It is the best way to make two controllers to talk to each other.
More on services : https://docs.angularjs.org/guide/services
create a service for directive B which will provide data for general messages.
inject that service into the underlying service of directive A. then call that service with proper message.
Directive A should auto display this data, because of 2 way data binding of angularjs.

Using 2 views and sharing data in AngularJS

Im trying to share data between 2 views. I need to use the 2 views at the same time on two different machines. One is controlling the other(ex: a counter) 1st view has next(+1) and the other just displays the result. I want the data to synchronized/binded. I do not want to have to refresh the 2nd page or to have to pull data with a timer or otherwise.
My idea was to use ng-view and routeProvider, I know that when the view changes the scope is cleared so I tried to use a parent controller/scope, the data is shared but I have to refresh the page on my 2nd view. I tried a service, same thing. I tried to $watch the result of the service but on the second controller/view no event is picked up so the view doesn't update.
what is the way to go? I was thinking about broadcasting or emit a custom event and trying to catch it, will that work? Am I just not binding to the service correctly? Would ui-router work better? I feel there should be an easy way to do this.... Im not seeing it! Please help if you can.
One of the simplest (in my opinion) implementations of client-client communication is using WebSockets. While that does have compatibility limitations (some browsers), that can easily be overcome by using a library like socket.io. Also, it's easy to write an Angular wrapper/service over socket.io that can be shared across components of your app, or even different modules.
It's also pretty simple to write a Node backend with socket.io
This might be a good read.
I would suggest you to focus on pushing stream rather than sharing it. Some how you need to push stream to second view which is changes in first view.
You may want to check this
Is there some way to PUSH data from web server to browser?

Resources