The method of ANGULARJS controller controller correct communication _angularjs

Source: Internet
Author: User
Tags emit event listener

Angularjs is a very powerful front-end MVC framework, ANGULARJS Controller is a function to add additional functionality to the scope of the view ($scope), which we use to set the initial state of the scope object and add custom behavior.

When we create a new controller, ANGULARJS will help us generate and pass a new $scope object to this controller, in any part of the ANGULARJS application, there is a parent scope, and the top-level is the level of the Ng-app. Its parent scope is $rootscope.

Each $scope $root points to $rootscope, $cope. $parent point to the parent scope.

The communication between Cotroller is essentially how the current controller $scope communicates with $scope on other controller.

There are usually 3 solutions:

Using the principle of scope inheritance, the child controller accesses the contents of the parent controller. Using the events in Angularjs, that is, using $on, $emit, $broadcast message delivery using services in ANGULARJS
The first way

Scope nesting scope, there are certain restrictions on the use of scopes, need to nest, in the actual development of this scenario relatively few, but also not without, this way more straightforward.

Angularjs by default, when a property cannot be found in the current scope, it is searched in the parent scope, if it is not found until the $rootscope is located. If you cannot find the program still running in $rootscope, the view is not 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"}

The second way

Because scopes are layered, you can pass events by using the scope chain.

There are 2 ways to deliver events: * $broadcast: Triggered events notify the entire event system (allowing any scope to handle this event) to propagate downward. * $emit: If you want to alert a global module, you need to notify a higher level of scope (for example, $rootscope) to pass the event up.

Use $on for event monitoring on scopes.

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 here to say is the performance of event propagation, $broadcast + $on way to notify all child scopes, there will be performance problems, so recommend the use of $emit+ $on way, in order to further improve performance, The defined event handler functions are released together when the scope is destroyed.

Using the $emit+ $on requires that we bind the event listener to the $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);
}
];

But this is a bit cumbersome, and it's not good to define multiple event handlers, so let's improve the

Use adorners 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;
}]);

So when we define the event handler function in the controller:

Javascript

Angular
. Module (' MyApp ')
. Controller (' Mycontroller ', [' $scope ', function Mycontroller ($scope) {
$scope . $onRootScope (' Somecomponent.somecrazyevent ', function () {
console.log (' foo ');
})

This practice is strongly recommended by individuals

The Third Way

Using the characteristics of the service single example mode in Angularjs, services provide a way to maintain data throughout the application lifecycle, communicate between controllers, and ensure data consistency.

Typically, we encapsulate the server to provide access to the data for the application, or to interact with the 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";
}
});

The above mentioned is for ANGULARJS controller controller Correct communication method, hope to be able to help everybody.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.