AngularJs: Controller data sharing, inheritance, and communication usage
Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka
Abstract: This article focuses on the detailed use of data sharing, inheritance, and communication in the Controller in AngularJs.
This tutorial uses AngularJs version: 1.5.3
AngularJs GitHub: https://github.com/angular/angular.js/
AngularJs: https://angularjs.org/
I. basics and usage of controller
The controller in AngularJS is the controller in Chinese. It is a Javascript function (type/class) used to add additional functions to the view scope ($ scope. In addition, each controller has its own scope, and can also share data in the scope of its parent controller.
Its functions are as follows:
(1) set the initial state for the scope object
You can create a model attribute to set the initial state of the initial scope. For example:
Var app = angular. module ('myapp', []); app. controller ('mycontroller', function ($ scope) {$ scope. inputValue = "Lin bingwen Evankaka ";});
We have set an inputValue above. To use it on an html page, you can use {inputValue} as follows:
The content you entered is: {inputValue }}
Of course, you can also bind the data to an input, select, and so on, as follows:
(2) Add actions to the scope object
AngularJS scope object behavior is represented by the scope method. These methods can be called in templates or views. These methods interact with the application model and change the model.
As we mentioned in the model chapter, any object (or native type) is assigned to the scope and then becomes a model. Any method assigned to the scope can be called in the template or view, and can be called through expressions or ng event instructions. As follows:
var app = angular.module('myApp', []);app.controller('myController', function($scope) { $scope.myClick = function(){ alert("click"); }});
Then use the following command on the page:
In this way, a click event is added to the button.
Ii. controller inheritance
The inheritance mentioned here generally refers to the scope data, because the scope of the sub-controller will prototype inherit the scope of the parent controller. Therefore, when you need to reuse features from the parent controller, all you need to do is add the corresponding methods in the parent scope. In this way, the self-controller obtains all methods in the parent scope through the prototype of its scope.
Example:
AngularJS getting started<Script type = "text/javascript" src = "./1.5.3/angular. min. js"> </script> Enter content
The content you entered is: {value1 }} <Script type = "text/javascript"> var app = angular. module ('myapp', []); // obtain the html element app affected by angularJS. controller ('parentctrl ', function ($ scope) {$ scope. value2 = "I am Lin bingwen" ;}); app. controller ('childctrl ', function ($ scope) {$ scope. gerParentValue = function () {alert ($ scope. value1 + $ scope. value2) ;}}); </script>
Note that the DIV where childCtrl is located must be placed in the DIV where parentCtrl is located to take effect! And if you need to call the sub-Controller method from the parent controller, the above Code will cause an error.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48aDE + rewrite + PHByZSBjbGFzcz0 = "brush: java;"> AngularJS getting started<Script type = "text/javascript" src = "./1.5.3/angular. min. js"> </script> {Name }} Set name to jack{Name }} Set name to tom <Script type = "text/javascript"> var app = angular. module ('myapp', []); app. controller ('paretnctrl ', function ($ scope, $ timeout) {$ scope. name = "Lin bingwen Evankaka" ;}); app. controller ('childctrl1', function ($ scope, $ timeout) {$ scope. setName = function () {$ scope. name = "set name to jack" ;};}); app. controller ('childctrl2 ', function ($ scope, $ timeout) {$ scope. setName = function () {$ scope. name = "set name to tom" ;}}); </script>
(2) share data globally
Angularjs has two ways to set global variables. In addition, there are three methods to set global variables in js. The function to be implemented is that global variables defined in ng-app can be used in different ng-controllers.
Using var to directly define global variable, this pure js is the same.
Use angularjs value to set global variables.
Use angularjs constant to set global variables.
The following describes how to use value.
AngularJS getting started<Script type = "text/javascript" src = "./1.5.3/angular. min. js"> </script>{Name }}Set name to jack{Name }}Set name to tom <Script type = "text/javascript"> var app = angular. module ('myapp', []); app. value ('data', {'name': 'I am Lin bingwen'}); app. controller ('childctrl1', function ($ scope, data) {$ scope. name = data. name; $ scope. setName = function () {$ scope. name = "set name to jack" ;};}); app. controller ('childctrl2 ', function ($ scope, data) {$ scope. name = data. name; $ scope. setName = function () {$ scope. name = "set name to tom" ;}}); </script>
(3) service dependency Injection
One of the most prominent features of angularjs is DI, Which is injection. The service is used to inject the data to be shared to the desired controller. This is the best method
AngularJS getting started<Script type = "text/javascript" src = "./1.5.3/angular. min. js"> </script>{Name }}Set name to jack{Name }}Set name to tom <Script type = "text/javascript"> var app = angular. module ('myapp', []); app. factory ('dataservice ', function () {var service = {name:' I am Lin bingwen'}; return service;}); app. controller ('chilctrl1', function ($ scope, dataService) {$ scope. name = dataService. name; $ scope. setName = function () {$ scope. name = "set name to jack" ;};}); app. controller ('childctrl2 ', function ($ scope, dataService) {$ scope. name = dataService. name; $ scope. setName = function () {$ scope. name = "set name to tom" ;}}); </script>
4. Communication between controllers
In general, the inheritance-based method is sufficient for most cases, but this method does not implement the communication mode between brother controllers, so the event mode is introduced. In the event-based approach, we can implement the $ on, $ emit, and $ boardcast modes, where $ on indicates event listening, and $ emit indicates to the parent level or above.
Event triggered by scope, $ boardcast indicates to broadcast events to the scope below the child level.
$ Emit can only pass events and data to the parent controller
$ Broadcast can only pass events and data to the child controller
$ On is used to receive events and data.
Instance 1:
AngularJS getting started<Script type = "text/javascript" src = "./1.5.3/angular. min. js"> </script>ChildCtr1 name:From childCtr1 name: <Script type = "text/javascript"> var app = angular. module ('myapp', []); app. controller ("parentCtr", function ($ scope) {$ scope. $ on ("Ctr1NameChange", function (event, msg) {// receives information from the Child childCtr1 and broadcasts it to all the sub-controller consoles. log ("parent", msg); $ scope. $ broadcast ("Ctr1NameChangeFromParrent", msg); // broadcast to all sub-controllers}); app. controller ("childCtr1", function ($ scope) {$ scope. change = function (name) {console. log ("childCtr1", name); $ scope. $ emit ("Ctr1NameChange", name); // pass the information to the parent controller };}). controller ("childCtr2", function ($ scope) {$ scope. $ on ("Ctr1NameChangeFromParrent", function (event, msg) {// listen to information console from the parent controller. log ("childCtr2", msg); $ scope. ctr1Name = msg;}) ;}); </script>
Example 2:
AngularJS getting started<Script type = "text/javascript" src = "./1.5.3/angular. min. js"> </script>
Click me
<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); // The value can be obtained at the parent level}); $ scope. $ on ('to-child ', function (event, data) {console. log ('parentctrl ', data); // The Sub-level cannot get the value}); app. controller ('childctrl ', function ($ scope) {$ scope. $ on ('to-child ', function (event, data) {console. log ('childctrl ', data); // The Sub-level can get the value}); $ scope. $ on ('to-parent', function (event, data) {console. log ('childctrl ', data); // The parent cannot get the value}); app. controller ('broctrl ', function ($ scope) {$ scope. $ on ('to-parent', function (event, data) {console. log ('broctrl ', data); // The value cannot be obtained at the level}); $ scope. $ on ('to-child ', function (event, data) {console. log ('broctrl ', data); // The level cannot be obtained}) ;}); </script>
Output result:
$ Emit and $ broadcast can pass multiple parameters, and $ on can also receive multiple parameters.
For the event parameter in the $ on method, the attributes and methods of the object are as follows:
Event attributes |
Purpose |
Event.tar getScope |
Scope of the original event |
Event. currentScope |
Scope of the event currently being processed |
Event. name |
Event name |
Event. stopPropagation () |
A function that prevents further event propagation (bubble/capture) (this is only applicable to events sent using '$ emit) |
Event. preventDefault () |
This method does not actually do anything, but sets 'defaultprevented' to true. It checks the value of 'defaultprediction' until the event listener's implementer takes action. |
Event. defaultPrevented |
If you call |
5. Suggestions for the controller Layer
1. The controller layer does not involve too much business logic. You can extract public parts to the Service layer.
2. service layer: mainly responsible for data interaction and data processing, and processing logic in some business fields;
3. controller layer: initializes the $ scope variable to be passed to the view layer and processes the logic generated by PAGE interaction;
4. When a function is to design Remote API calls, datasets, and complex business logic, and there will be a large number of repeated calculation methods, you can consider injecting code into the controller layer as a service.
5. $ scope in the controller is the only page data source. Do not directly modify the DOM.
6. controller should not be in the global scope
References:
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