Angular Js: Controller Data Sharing, Inheritance, Communication Usage Details

Abstract: This article is the main topic. AngularJS Detailed Use of Data Sharing, Inheritance and Communication in Controller

Use of this tutorial angularjs Version: 1.5.3

AngularJs GitHub: https://github.com/angular/angular.js/

Angular Js Download Address: https://angularjs.org/

I. The Basis and Usage of controller

The Chinese name of controller in Angular JS is controller. It is a controller. JavaScript Function (type/class) to add additional functionality to the scope of the view ($scope). And each controller has its own scope. They can also share data within their father controller's scope.

Its functions are as follows:

(1) Setting the initial state of the scoped object

You can set the initial state of the initial scope by creating a model attribute. For example:

  1. var app = angular.module('myApp', []);  
  2. app.controller('myController', function($scope) {  
  3.     $scope.inputValue = "Pin-Wen Lin Evankaka";  
  4. });  
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
    $scope.inputValue = "Pin-Wen Lin Evankaka";
});
Above we set up an inputValue. If you want to use it in html pages, you can use {inputValue} directly, as follows:

  1. <h1> The content you entered is: {inputValue}</h1>
<h1> The content you entered is: {inputValue}</h1>
Of course, you can also bind this data to an input, select, and so on, as follows:

  1. <input  type="text" ng-model = "inputValue">  
<input  type="text" ng-model = "inputValue">

(2) Adding behavior to scoped objects


The behavior of Angular JS scoped objects is represented by scoped methods. These methods can be invoked in templates or views. These methods interact with application models and can change them.
As we said in the chapter on models, any object (or primitive type) that is assigned scope becomes a model. Any scoped method can be invoked in a template or view, and can be invoked through expressions or ng event instructions. As follows:

  1. var app = angular.module('myApp', []);  
  2. app.controller('myController', function($scope) {  
  3.     $scope.myClick = function(){  
  4.         alert("click");  
  5.     }  
  6. });  
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
    $scope.myClick = function(){
    	alert("click");
    }
});
Then use on the page:

  1. <button ng-click"myClick()" ></button>    
<button ng-click= "myClick()" ></button>  
This adds a click event to the button


II. controller Inheritance

Inheritance here is generally referred to as scope data, because the scope of the sub-controller will prototype inherit the scope of the parent controller. So when you need to reuse functionality from the parent controller, all you need to do is add methods to the parent scope. In this way, the self-controller will obtain all the methods in the parent scope through the prototype of its scope.

The following examples are given:

  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS Introductory Learning</title>  
  6.     <script type="text/javascript"  src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9.     <div ng-controller = "parentCtrl">  
  10.         <p><input  type="text" ng-model = "value1">Please enter the content</p>  
  11.         <h1>The content you entered is:{{value1}}</h1>  
  12.           <div ng-controller = "childCtrl">  
  13.             <button ng-click = "gerParentValue()"></button>  
  14.           </div>  
  15.     </div>  
  16.   
  17. </body>  
  18. <script type="text/javascript">  
  19. var app = angular.module('myApp', []);//Get the html elements that affect the entire angular JS
  20. app.controller('parentCtrl',function($scope){  
  21.     $scope.value2 = "I'm Lin Bingwen.";  
  22. });    
  23.   
  24. app.controller('childCtrl',function($scope){  
  25.     $scope.gerParentValue = function() {  
  26.         alert($scope.value1 + $scope.value2);  
  27.     }  
  28. });   
  29. </script>  
  30. </html>  
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
	<meta charset="UTF-8">
	<title>AngularJS Introductory Learning</title>
	<script type="text/javascript"  src="./1.5.3/angular.min.js"></script>
</head>
<body>
    <div ng-controller = "parentCtrl">
	    <p><input  type="text" ng-model = "value1">Please enter the content</p>
	    <h1>The content you entered is:{{value1}}</h1>
	      <div ng-controller = "childCtrl">
		    <button ng-click = "gerParentValue()"></button>
	      </div>
	</div>

</body>
<script type="text/javascript">
var app = angular.module('myApp', []);//Get the html elements that affect the entire angular JS
app.controller('parentCtrl',function($scope){
    $scope.value2 = "I'm Lin Bingwen.";
});  

app.controller('childCtrl',function($scope){
    $scope.gerParentValue = function() {
    	alert($scope.value1 + $scope.value2);
    }
}); 
</script>
</html>


It should be noted here that the DVI of child Ctrl must be placed in the DVI of parent Ctrl before it takes effect! And if you need to call the method of the sub-controller from the parent controller, then using the above code will cause errors.


3. Sharing data between controller s

(1) Define scope in parent controller and share it with children

  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS Introductory Learning</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9.    <div  ng-controller="paretnCtrl">  
  10.      <input type="text" ng-model="name" />  
  11.      <div ng-controller="childCtrl1">  
  12.         {{name}}  
  13.         <button ng-click="setName()">set name to jack jack jack</button>  
  14.      </div>  
  15.      <div ng-controller="childCtrl2">  
  16.         {{name}}  
  17.         <button ng-click="setName()">set name to tom tom tom</button>  
  18.      </div>  
  19.    </div>  
  20. </body>  
  21. <script type="text/javascript">  
  22. var app = angular.module('myApp', []);  
  23. app.controller('paretnCtrl', function($scope,$timeout) {  
  24.     $scope.name = "Pin-Wen Lin Evankaka";  
  25. });  
  26. app.controller('childCtrl1', function($scope,$timeout) {  
  27.     $scope.setName = function() {  
  28.          $scope.name = "set name to jack jack jack";  
  29.     };  
  30. });  
  31. app.controller('childCtrl2', function($scope,$timeout) {  
  32.     $scope.setName = function() {  
  33.         $scope.name = "set name to tom tom tom";  
  34.     };  
  35. });  
  36. </script>  
  37. </html>  
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Introductory Learning</title>
    <script type="text/javascript" src="./1.5.3/angular.min.js"></script>
</head>
<body>
   <div  ng-controller="paretnCtrl">
     <input type="text" ng-model="name" />
     <div ng-controller="childCtrl1">
        {{name}}
        <button ng-click="setName()">set name to jack jack jack</button>
     </div>
     <div ng-controller="childCtrl2">
        {{name}}
        <button ng-click="setName()">set name to tom tom tom</button>
     </div>
   </div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('paretnCtrl', function($scope,$timeout) {
    $scope.name = "Pin-Wen Lin Evankaka";
});
app.controller('childCtrl1', function($scope,$timeout) {
    $scope.setName = function() {
         $scope.name = "set name to jack jack jack";
    };
});
app.controller('childCtrl2', function($scope,$timeout) {
    $scope.setName = function() {
    	$scope.name = "set name to tom tom tom";
    };
});
</script>
</html>

(2) Global sharing of data

Angular JS itself has two ways to set global variables, plus js There are three ways to set global variables. The function to achieve is that the global variables defined in ng-app can be used in different ng-controller s.
By defining global variable s directly through var, this pure js is the same.
Use angular JS value to set global variables.
Use angular JS constant to set global variables.

Here's how to use value

  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS Introductory Learning</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9.      <div ng-controller="childCtrl1">  
  10.         {{name}}  
  11.         <button ng-click="setName()">set name to jack jack jack</button>  
  12.      </div>  
  13.      <div ng-controller="childCtrl2">  
  14.         {{name}}  
  15.         <button ng-click="setName()">set name to tom tom tom</button>  
  16.      </div>  
  17. </body>  
  18. <script type="text/javascript">  
  19. var app = angular.module('myApp', []);  
  20. app.value('data',{'name':'I'm Lin Bingwen.'});  
  21. app.controller('childCtrl1', function($scope,data) {  
  22.     $scope.name = data.name;  
  23.     $scope.setName = function() {  
  24.          $scope.name = "set name to jack jack jack";  
  25.     };  
  26. });  
  27. app.controller('childCtrl2', function($scope,data) {  
  28.        $scope.name = data.name;  
  29.        $scope.setName = function() {  
  30.         $scope.name = "set name to tom tom tom";  
  31.     };  
  32. });  
  33. </script>  
  34. </html>  
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Introductory Learning</title>
    <script type="text/javascript" src="./1.5.3/angular.min.js"></script>
</head>
<body>
     <div ng-controller="childCtrl1">
        {{name}}
        <button ng-click="setName()">set name to jack jack jack</button>
     </div>
     <div ng-controller="childCtrl2">
        {{name}}
        <button ng-click="setName()">set name to tom tom tom</button>
     </div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.value('data',{'name':'I'm Lin Bingwen.'});
app.controller('childCtrl1', function($scope,data) {
	$scope.name = data.name;
    $scope.setName = function() {
         $scope.name = "set name to jack jack jack";
    };
});
app.controller('childCtrl2', function($scope,data) {
	   $scope.name = data.name;
       $scope.setName = function() {
    	$scope.name = "set name to tom tom tom";
    };
});
</script>
</html>

(3) service dependency injection

One of the most prominent features of angular JS is DI, i.e. injection, which uses service to inject data that needs to be shared into the required controller. This is the best way.

  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS Introductory Learning</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9.      <div ng-controller="childCtrl1">  
  10.         {{name}}  
  11.         <button ng-click="setName()">set name to jack jack jack</button>  
  12.      </div>  
  13.      <div ng-controller="childCtrl2">  
  14.         {{name}}  
  15.         <button ng-click="setName()">set name to tom tom tom</button>  
  16.      </div>  
  17. </body>  
  18. <script type="text/javascript">  
  19. var app = angular.module('myApp', []);  
  20. app.factory('dataService', function() {  
  21.   var service = {  
  22.      name:'I'm Lin Bingwen.'  
  23.    };  
  24.    return service;  
  25. });  
  26. app.controller('childCtrl1', function($scope,dataService) {  
  27.     $scope.name = dataService.name;  
  28.     $scope.setName = function() {  
  29.          $scope.name = "set name to jack jack jack";  
  30.     };  
  31. });  
  32. app.controller('childCtrl2', function($scope,dataService) {  
  33.        $scope.name = dataService.name;  
  34.        $scope.setName = function() {  
  35.         $scope.name = "set name to tom tom tom";  
  36.     };  
  37. });  
  38. </script>  
  39. </html>  
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Introductory Learning</title>
    <script type="text/javascript" src="./1.5.3/angular.min.js"></script>
</head>
<body>
     <div ng-controller="childCtrl1">
        {{name}}
        <button ng-click="setName()">set name to jack jack jack</button>
     </div>
     <div ng-controller="childCtrl2">
        {{name}}
        <button ng-click="setName()">set name to tom tom tom</button>
     </div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.factory('dataService', function() {
  var service = {
     name:'I'm Lin Bingwen.'
   };
   return service;
});
app.controller('childCtrl1', function($scope,dataService) {
	$scope.name = dataService.name;
    $scope.setName = function() {
         $scope.name = "set name to jack jack jack";
    };
});
app.controller('childCtrl2', function($scope,dataService) {
	   $scope.name = dataService.name;
       $scope.setName = function() {
    	$scope.name = "set name to tom tom tom";
    };
});
</script>
</html>

Communication between controller s

In general, the inheritance-based approach is sufficient for most cases, but it does not realize the communication between sibling controllers, so it leads to the way of events. In the event-based approach, we can implement the functions of $on,$emit,$boardcast, where $on means event listener and $emit means parent or higher.
Scope triggers events, $boardcast represents broadcast events to scopes below the child level.

$emit can only pass event and data to parent controller
$broadcast can only pass event and data to child controller
$on is used to receive event and data

Example 1:

  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS Introductory Learning</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <div ng-app="app" ng-controller="parentCtr">  
  10.      <div ng-controller="childCtr1">childCtr1 name :  
  11.          <input ng-model="name" type="text" ng-change="change(name)" />  
  12.     </div>  
  13.      <div ng-controller="childCtr2">from childCtr1 name:  
  14.          <input ng-model="ctr1Name" />  
  15.      </div>  
  16. </div>  
  17. </body>  
  18. <script type="text/javascript">  
  19. var app = angular.module('myApp', []);  
  20. app.controller("parentCtr",function ($scope) {  
  21.     $scope.$on("Ctr1NameChange",function (event, msg) {//Receive information from child Ctr1 and broadcast it to all child controller s.
  22.         console.log("parent", msg);  
  23.         $scope.$broadcast("Ctr1NameChangeFromParrent", msg);//Broadcast to all sub-controller s
  24.     });  
  25. });  
  26. app.controller("childCtr1", function ($scope) {  
  27.     $scope.change = function (name) {  
  28.         console.log("childCtr1", name);  
  29.         $scope.$emit("Ctr1NameChange", name);//Pass the information to the parent controller
  30.     };  
  31. }).controller("childCtr2", function ($scope) {  
  32.     $scope.$on("Ctr1NameChangeFromParrent",function (event, msg) { //Listen for information from father controller
  33.         console.log("childCtr2", msg);  
  34.         $scope.ctr1Name = msg;  
  35.     });  
  36. });  
  37. </script>  
  38. </html>  
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Introductory Learning</title>
    <script type="text/javascript" src="./1.5.3/angular.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="parentCtr">
     <div ng-controller="childCtr1">childCtr1 name :
         <input ng-model="name" type="text" ng-change="change(name)" />
    </div>
     <div ng-controller="childCtr2">from childCtr1 name:
         <input ng-model="ctr1Name" />
     </div>
</div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("parentCtr",function ($scope) {
    $scope.$on("Ctr1NameChange",function (event, msg) {//Receive information from child Ctr1 and broadcast it to all child controller s
        console.log("parent", msg);
        $scope.$broadcast("Ctr1NameChangeFromParrent", msg);//Broadcast to all sub-controller s
    });
});
app.controller("childCtr1", function ($scope) {
    $scope.change = function (name) {
        console.log("childCtr1", name);
        $scope.$emit("Ctr1NameChange", name);//Pass information to parent controller
    };
}).controller("childCtr2", function ($scope) {
    $scope.$on("Ctr1NameChangeFromParrent",function (event, msg) { //Listening for information from father controller
        console.log("childCtr2", msg);
        $scope.ctr1Name = msg;
    });
});
</script>
</html>

Example 2:

  1. <!DOCTYPE html>  
  2. <html lang="zh" ng-app="myApp">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>AngularJS Introductory Learning</title>  
  6.     <script type="text/javascript" src="./1.5.3/angular.min.js"></script>  
  7. </head>  
  8. <body>  
  9. <div ng-controller="ParentCtrl">                <!--Father level-->  
  10.     <div ng-controller="SelfCtrl">              <!--Own-->  
  11.          <button ng-click="click()">click me</button>  
  12.         <div ng-controller="ChildCtrl">  
  13.               
  14.         </div>   <!--Sub level-->  
  15.     </div>  
  16.     <div ng-controller="BroCtrl">  
  17.           
  18.     </div>         <!--Level-->  
  19. </div>  
  20. </body>  
  21. <script type="text/javascript">  
  22. var app = angular.module('myApp', []);  
  23. app.controller('SelfCtrl', function($scope) {  
  24.   $scope.click = function () {  
  25.     $scope.$broadcast('to-child', 'child');  
  26.     $scope.$emit('to-parent', 'parent');  
  27.   }  
  28. });  
  29.   
  30. app.controller('ParentCtrl', function($scope) {  
  31.   $scope.$on('to-parent', function(event,data) {  
  32.     console.log('ParentCtrl', data);       //Parents get values.
  33.   });  
  34.   $scope.$on('to-child', function(event,data) {  
  35.     console.log('ParentCtrl', data);       //The sublevel does not get a value.
  36.   });  
  37. });  
  38.   
  39. app.controller('ChildCtrl', function($scope){  
  40.   $scope.$on('to-child', function(event,data) {  
  41.     console.log('ChildCtrl', data);      //Sublevel can get value.
  42.   });  
  43.   $scope.$on('to-parent', function(event,data) {  
  44.     console.log('ChildCtrl', data);      //Parents do not get values.
  45.   });  
  46. });  
  47.   
  48. app.controller('BroCtrl', function($scope){    
  49.   $scope.$on('to-parent', function(event,data) {    
  50.     console.log('BroCtrl', data);         //Level is not valued.
  51.   });    
  52.   $scope.$on('to-child', function(event,data) {    
  53.     console.log('BroCtrl', data);         //Level is not valued.
  54.   });    
  55. });  
  56. </script>  
  57. </html>  
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Introductory Learning</title>
    <script type="text/javascript" src="./1.5.3/angular.min.js"></script>
</head>
<body>
<div ng-controller="ParentCtrl">                <!--Father level-->
    <div ng-controller="SelfCtrl">              <!--Own-->
         <button ng-click="click()">click me</button>
        <div ng-controller="ChildCtrl">
        	
        </div>   <!--Sub level-->
    </div>
    <div ng-controller="BroCtrl">
    	
    </div>         <!--Level-->
</div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('SelfCtrl', function($scope) {
  $scope.click = function () {
    $scope.$broadcast('to-child', 'child');
    $scope.$emit('to-parent', 'parent');
  }
});

app.controller('ParentCtrl', function($scope) {
  $scope.$on('to-parent', function(event,data) {
    console.log('ParentCtrl', data);	   //Parents can get values
  });
  $scope.$on('to-child', function(event,data) {
    console.log('ParentCtrl', data);	   //The sublevel does not get a value
  });
});

app.controller('ChildCtrl', function($scope){
  $scope.$on('to-child', function(event,data) {
    console.log('ChildCtrl', data);		 //Sublevel can get value
  });
  $scope.$on('to-parent', function(event,data) {
    console.log('ChildCtrl', data);		 //Parents do not get values
  });
});

app.controller('BroCtrl', function($scope){  
  $scope.$on('to-parent', function(event,data) {  
    console.log('BroCtrl', data);		  //Level can't get value  
  });  
  $scope.$on('to-child', function(event,data) {  
    console.log('BroCtrl', data);		  //Level can't get value  
  });  
});
</script>
</html>
Output results:


$emit and $broadcast can pass multiple parameters, and $on can receive multiple parameters.

The event event event parameter in the $on method has the following attributes and methods for the object

Event attributes objective
event.targetScope Scope of sending out or disseminating the original event
event.currentScope Scope of events currently being addressed
event.name Event name
event.stopPropagation() A function that prevents further propagation of events (bubbles/traps) (this applies only to events emitted using `emit')
event.preventDefault() This method doesn't actually do anything, but it sets `default Prevented'to true. It does not check the `defaultPrevented'value until the event listener implementer takes action.
event.defaultPrevented If called

5. Some Suggestions for the controller Layer

1. controller layer does not involve too much business logic. It can extract common parts to Service layer.

2. service layer: mainly responsible for data interaction and data processing, processing logic in some business areas;
3. controller layer: It is mainly responsible for initializing the variables of $scope to pass to view layer, and handling some logic generated by page interaction.
4. When a function is to design remote API calls, data sets, business insights into complex logic, will be a large number of repetitive computing methods, you can consider injecting code into the controller layer in the form of service.

5. The $scope in the controller is the only source of page data. Do not modify DOM directly.

6. controller should not be global


Reference article:

http://www.jianshu.com/p/1e1aaf0fd30a

http://cnodejs.org/topic/54dd47fa7939ece1281aa54f

http://www.html-js.com/article/1847

http://blog.51yip.com/jsjquery/1601.html

http://www.cnblogs.com/CraryPrimitiveMan/p/3679552.html?utm_source=tuicool&utm_medium=referral

http://www.cnblogs.com/whitewolf/archive/2013/04/16/3024843.html


Reprinted from: http://blog.csdn.net/evankaka/article/details/51097039


For more knowledge, welcome to join 651308349, 627336556 technology development exchange group, there will be unexpected gains ~!!!

Keywords: angular Javascript AngularJS github

Added by vynsane on Fri, 07 Jun 2019 00:43:21 +0300