AngularJS controller correct communication method, angularjs controller Communication

Source: Internet
Author: User

AngularJS controller correct communication method, angularjs controller Communication

AngularJS is a very powerful front-end MVC Framework. 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 behavior.

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

//Javascriptapp.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');});}]); 

I strongly recommend this practice.

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";}});

The above is a correct communication method for AngularJS controller, hoping to help you.

Articles you may be interested in:
  • AngularJs dynamic Controller loading solution based on the accessed page
  • Explanation of AngularJS Communication Mechanism
  • Angularjs learning notes Module 3 (modal, controller, view)
  • AngularJS Getting Started: direve VE and controller communication process

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.