Controller in AngularJS is a function used to add additional functions to the view scope ($ scope). We use it to set the initial state for the scope object and add custom behaviors.
When we create a new controller, angularJS will generate and pass a new $ scope object to this controller, in any part of angularJS application, the parent scope exists. The top level is the level where the ng-app is located, and its parent scope is $ rootScope.
$ Root of each $ scope points to $ rootScope, and $ parent. $ parent points to the parent scope.
The communication between cotroller is essentially how the $ scope of the current controller communicates with the $ scope of other controllers.
There are usually three solutions:
With the principle of scope inheritance, the sub-controller accesses the content in the parent controller. Use Events in angularJS, that is, use $ on, $ emit, and $ broadcast for message transmission. Use services in angularJS.
Method 1
That is, the scope nesting scope has certain restrictions and requires scope nesting. In actual development, this type of scenario is relatively small, but not absent. This method is simpler and more direct.
In angularJS, by default, when an attribute cannot be found in the current scope, it will be searched in the parent scope. If it cannot be found until $ rootScope is found. If you cannot find the program still running in $ rootScope, but the view will not be updated.
Example
Javascript
// Javascript
App. controller ('parentcontroller', function ($ scope ){
$ Scope. person = {greeted: false };
});
App. controller ('childcontroller', function ($ scope ){
$ Scope. sayHello = function (){
$ Scope. person. name = 'Ari Lerner ';
};
});
// HTML
<Div ng-controller = "ParentController">
<Div ng-controller = "ChildController">
<A ng-click = "sayHello ()"> Say hello </a>
</Div>
{Person }}
</Div>
// Result
{"Greeted": true, "name": "Ari Lerner "}
Method 2
Because the scope is hierarchical, you can use the scope chain to pass events.
There are two ways to pass an event: * $ broadcast: the event to be triggered must be notified to the entire event system (to allow any scope to handle this event. * $ Emit: to notify a global module of a higher level scope (for example, $ rootscope), the event must be passed up.
$ On is used for event listening in the scope.
Example
JavaScript
App. controller ('parentcontroller', function ($ scope ){
$ Scope. $ on ('$ fromsubcontrollerclick', function (e, data ){
Console. log (data); // hello
});
});
App. controller ('childcontroller', function ($ scope ){
$ Scope. sayHello = function (){
$ Scope. $ emit ('$ fromsubcontrollerclick', 'Hello ');
};
});
// HTML
<Div ng-controller = "ParentController">
<Div ng-controller = "ChildController">
<A ng-click = "sayHello ()"> Say hello </a>
</Div>
</Div>
Another problem to be mentioned here is the performance problem of event propagation. $ broadcast + $ on is used to notify all sub-scopes. Here there will be performance problems, therefore, we recommend that you use $ emit + $ on. To further improve the performance, the defined event handler function should be released when the scope is destroyed.
To use $ emit + $ on, we need to bind event listening to $ rootScope. For example:
JavaScript
Angular
. Module ('myapp ')
. Controller ('mycontroller', ['$ scope', '$ rootScope', function MyController ($ scope, $ rootScope ){
Var unbind = $ rootScope. $ on ('somecomponent. Somecrazyevent', function (){
Console. log ('Foo ');
});
$ Scope. $ on ('$ destroy', unbind );
}
]);
However, this method is a bit cumbersome. It is difficult to define multiple event processing functions, so let's improve it.
Use the decorator to define a new event binding function:
JavaScript
Angular
. Module ('myapp ')
. Config (['$ provide', function ($ provide ){
$ Provide. decorator ('$ rootScope', ['$ delegate', function ($ delegate ){
Object. defineProperty ($ delegate. constructor. prototype, '$ onRootScope ',{
Value: function (name, listener ){
Var unsubscribe = $ delegate. $ on (name, listener );
This. $ on ('$ destroy', unsubscribe );
Return unsubscribe;
},
Enumerable: false
});
Return $ delegate;
}]);
}]);
When we define the event processing function in the controller:
JavaScript
Angular
. Module ('myapp ')
. Controller ('mycontroller', ['$ scope', function MyController ($ scope ){
$ Scope. $ onRootScope ('somecomponent. Somecrazyevent', function (){
Console. log ('Foo ');
});
}
]). This is strongly recommended by individuals.
Method 3
Using the features of the service Singleton mode in angularJS, the service provides a way to maintain data throughout the entire lifecycle of an application, allowing communication between controllers, data consistency can be ensured.
Generally, we encapsulate the server to provide an interface for the application to access data, or to interact with remote data.
Example
JavaScript
Var myApp = angular. module ("myApp", []);
MyApp. factory ('data', function (){
Return {
Name: "Ting"
}
});
MyApp. controller ('firstctrl ', function ($ scope, Data ){
$ Scope. data = Data;
$ Scope. setName = function (){
Data. name = "Jack ";
}
});
MyApp. controller ('secondctrl ', function ($ scope, Data ){
$ Scope. data = Data;
$ Scope. setName = function (){
Data. name = "Moby ";
}
});
Use a simple method to summarize
1. Parent controller, responsible for listening and broadcasting
// Listener: if a change is received, broadcast the value.
$ Scope. $ on ("change", function (event, msg ){
$ Scope. $ broadcast ("changeFromBody", msg );
});
2. The sub-controller sends the variable to the parent controller.
// Pass the value $ scope. value to the parent controller
$ Scope. $ emit ("change", $ scope. value );
3. The sub-controller monitors the broadcast of the parent controller and adds new values to the variables.
// Listen to the broadcast of the parent controller and get $ scope. value for the changeFromBody broadcast.
$ Scope. $ on ("changeFromBody", function (event, msg ){
$ Scope. value = msg;
});