Preface
As a bridge between M and V in the angularJS framework MVC, controller plays an important role in the entire angularJS web application.
Usually we can use a singleton service to share data in different controllers. For example, in controller1, the value in the service is modified through the click event, and in controller2, the value modified through the click event is obtained, which realizes the transfer of a value. However, if the click event is not set in controller2, how can I achieve the automatic acquisition of the new value when the value is modified in controller1?
For example, there is a scenario where you have a service where the data you need is stored. You have a list view A and a data display view B. You control the two views through the two controllers Actl and Bctl, and Actl and Bctl have a common parent ctl. When you click on different list items in list view A, data display view B will synchronize the service to obtain the corresponding data according to the different list items you selected and display it on your own view interface.
Use the $on, $broadcast, and $emit methods to achieve synchronous refresh of different view interfaces
angularJS provides a complete set of event propagation methods used to pass events and data in different controllers.
$on is used to monitor events propagated from children or parent scopes and corresponding data in scope.
The format is as follows: $on(event,data);
The purpose of $broadcast is to propagate events from the parent scope to the child scope, including itself.
The format is as follows: $broadcast(eventName,args);
The purpose of $emit is to propagate events from the child scope to the parent scope, including itself until the root scope.
The format is as follows: $emit(eventName,args);
The above three methods can be used to realize the requirements of our scenario.
The method is as follows:
1. In list view A, use a form such as $emit('fresh',data) to launch an event, data can be the number of the list item you selected, etc.
2. Listen to the event through $on on the parent ctl, get the data passed on the list view A, and then broadcast the event downward through $broadcast
3. In data display view B, listen to the event type of parent ctl broadcast, use the obtained data value in the callback function to get the corresponding data in the service, and then refresh the view using the $apply method.
The above detailed explanation of the angularJS implementation of synchronous refresh of different views is all the content I share with you. I hope you can give you a reference and I hope you can support me more.