ANGULARJS Handout-Controller

Source: Internet
Author: User

In angular, the controller is a JavaScript-based construction method that is used primarily to construct the model and establish data binding between the model and the view. The controller defines the logic and behavior of the application.

The Ng-controller directive allows you to bind the controller and the DOM together. Angular instantiates a controller object with a defined controller constructor, creating a root scope when the angular application (module) is started, angular creating a new child scope when instantiating each controller and serving as an injection parameter ($scope) Injected into the controller's construction method.

On the basis of understanding the function of the controller, we should use the controller as agreed:

1. Initialize the $scope.

2. Increase the behavior of the application in $scope.

Try to avoid using the controller in the following scenarios:

1. Operation Dom-the controller mainly contains the business logic. Putting the view logic into the controller can seriously affect the testability of the code. Angular has encapsulated most of the listener and DOM manipulation logic in data bindings and directives (directives).

2. Format input-replace with angular form controls as much as possible.

3. Format or filter output-consider using the angular filter (filters).

4. Implement shared code snippets, or manage state between multiple controllers-consider using service components to manage

5. Managing the life cycle of other components (for example, creating service component Instances)

Initializing the state of a $scope object

But when creating an app, we usually need to initialize the state of the angular $scope by setting the properties of the $scope. These attributes (properties) contain the view model. The properties of the $scope are visible within the bounds of the DOM that the Controller is bound to (template).

For example:

JS Code
1 var myApp = angular.module (' myApp ', []);    2 Myapp.controller (' Greetingcontroller ', [' $scope ', function ($scope) {  3   $scope. Greeting = ' hola! ';  

Here a ' myApp ' application module is created and the ' Greetingcontroller ' controller is defined, then we bind the controller to the corresponding Div via the ng-controller directive:

HTML code
1 <  ng-controller= "Greetingcontroller">  2  {{greeting}}   3 </ Div >  

This allows us to get the value of the Greeting property through the {{greeting}} expression.

Assigning behavior to scope objects

We can add methods to the scope object so that they can be called in response to an event or perform some computational tasks in a bound view or template. Let's look at the following example:

JS Code
1 var myApp = angular.module (' myApp ', []);  2   3 Myapp.controller (' Doublecontroller ', [' $scope ', function ($scope) {  4   $scope. Double = function (value) {return value * 2;};  

In this JS code, we add a double method to scope, and then we add the controller to the DOM:

HTML code
1 <  ng-controller= "Doublecontroller">  2   <   ng-model= "num">  equals {{double (num)}}  3 </ Div >  

This allows us to invoke the double method of scope through an expression. As we described in the Basic Concepts section, the properties defined in scope can be bound as model data, and the methods defined in scope can also be called by an expression or NG event instruction, such as Ngclick.

Correct use of the controller

in short, the controller typically contains only the view-related business logic. We can encapsulate the view-independent code and common code in the service, and use services by injecting dependencies in the constructor. We will explain the dependency injection mechanism in a later chapter.

Association controllers and scope objects

We can correlate controllers and scope objects with Ngcontroller directives and $route service.

Next we use code examples to help you better understand how the angular controller works. We will create a simple app that contains three sections:

1. A template contains a message and two buttons.

2. A model contains a property called Spice.

3. A controller contains two methods to set the value of spice.

Template code (index.html)

HTML code
1 <DivNg-controller= "Spicycontroller">  2  <ButtonNg-click= "Chilispicy ()">Chili</Button>  3  <ButtonNg-click= "Jalapenospicy ()">Jalapeño</Button>  4  <P>The food is {{spice}} spicy!</P>  5 </Div>  

App.js (Controller defined)

JS Code
1 var myApp = angular.module (' SpicyApp1 ', []);   3 Myapp.controller (' Spicycontroller ', [' $scope ', function ($scope) {   4     $scope. Spice = ' very ';   5    6     $scope. Chilispicy = function () {   7         $scope. Spice = ' chili ';   8     };     $scope. Jalapenospicy = function () {One         $scope. Spice = ' jalapeño ';     n};  

We can see that the message in the template is bound to the Spice property by the expression, spice is initialized to "very", and then we have the two methods in the scope bound by Ng-click, respectively, to modify the spice value, but when we click the button, the message is automatically refreshed.

To initialize a page:

When you click Chili, the message is updated automatically:


Let's summarize the above examples:

1. Angular creates a scope (scope) implicitly for the template by Ng-controller, and the scope is Spicycontroller expanded.

2. Spicycontroller is a normal JavaScript function. Usually the controller is capitalized with the first letter, and the controller is the suffix.

3. Create or update the model by assigning values to the attributes inside the $scope.

4. The Controller's method can be defined directly as a $scope method.

5. You can access the methods and properties of the controller through the expressions in the template and the NG event directives in the <div> and child elements associated with the controller.

Example two: Add a parameter to the Controller method, the parameter can refer to the model

HTML code
1 <DivNg-controller= "Spicycontroller">  2  <inputNg-model= "Customspice">  3  <ButtonNg-click= "spicy (' chili ')">Chili</Button>  4  <ButtonNg-click= "Spicy (customspice)">Custom Spice</Button>  5  <P>The food is {{spice}} spicy!</P>  6 </Div>  
Java code
1 var myApp = angular.module (' spicyApp2 ', []);   3 Myapp.controller (' Spicycontroller ', [' $scope ', function ($scope) {   4     $scope. Customspice = "Wasabi";   5     $scope. Spice = ' very ';   7     $scope. Spicy = function (Spice) {   8         $scope. Spice = Spice;   9     };  10}]);  

In this example we notice that the Ng-click binding method adds parameters to the value of the model spice, and the input text box is also bound to the spice attribute, but in the Input text box type the spice value, click the ' Custom Spice ' button, The value of spiced in the message is replaced with the value in the text box.

Example three: The inheritance relationship of scopes

We can associate the controller to different DOM levels. Because the ng-controller instruction automatically creates child scopes, the scope also has a corresponding hierarchical relationship. The properties and methods in the parent scope can be accessed in the child scope, and the properties and methods of the same name in the ancestor scope hide the quilt scope. Let's combine the code to understand:

Index.html

Index.html Code
1 <Divclass= "Spicy">  2   <DivNg-controller= "Maincontroller">  3     <P>Good {{TimeOfDay}}, {{name}}!}</P>  4   5     <DivNg-controller= "Childcontroller">  6       <P>Good {{TimeOfDay}}, {{name}}!}</P>  7   8       <DivNg-controller= "Grandchildcontroller">  9         <P>Good {{TimeOfDay}}, {{name}}!}</P>  Ten       </Div>   One     </Div>   A   </Div>   - </Div>  

App.css

APP.CSS Code

1 div.spicy div { 2 padding: 10px; 3 border: solid 2px Blue; 4 }

App.js

App.js Code
1 var myApp = angular.module (' Scopeinheritance ', []);   2 Myapp.controller (' Maincontroller ', [' $scope ', function ($scope) {   3   $scope. TimeOfDay = ' morning ';   4   $scope. Name = ' Nikki ';   5}]);   6 Myapp.controller (' Childcontroller ', [' $scope ', function ($scope) {   7   $scope. Name = ' Mattie ';   8}]);   9 Myapp.controller (' Grandchildcontroller ', [' $scope ', function ($scope) {  ten   $scope. TimeOfDay = ' evening ';   $scope. Name = ' Gingerbread Baby ';  

Operation Result:

We notice here that we have implemented three controllers: Maincontroller, Childcontroller, Grandchildcontroller, and are associated in different levels of Div, angular will produce four scopes:

1. Root scope

2. Scope of the Maincontroller, including the TimeOfDay and name properties.

3. The scope of Childcontroller, which inherits the TimeOfDay property of Maincontroller, overrides the Maincontroller Name property.

4. The scope of Grandchildcontroller, which inherits the TimeOfDay attribute from the Maincontroller scope, overrides the Name property of the previous scope.

The method principle in the scope is the same as above, here is not a detailed explanation.

ANGULARJS Handout-Controller

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.