04 controller-AngularJS basic tutorial,-angularjs basic tutorial

Source: Internet
Author: User

04 controller-AngularJS basic tutorial,-angularjs basic tutorial
0. Directory

  • Directory
  • Preface
  • Body
    • 1 ng-controller
    • 2. Build a model-Constructing the model
    • 3. Controller as the property name-Controller as propertyName
    • 4. Dependency injection-Dependency injection
      • 41 scope
    • 5. Model view controller MVC-Model-view-controller
    • 6 Functions-Functions
    • 7. Callback Function
    • 8 conclusion
  • Statement

1. Preface

AngularJS is designed to overcome the shortcomings of HTML in building applications. HTML is a well-designed declarative language for static text display, but it seems weak to build WEB applications, angularJS has done some work to solve the shortcomings of static Web Page Technology in building dynamic applications.

AngularJS was originally designedSimplify web APP development, The essence isSimple. However, there are many AngularJS tutorials at home and abroad, all focusing on the strengths of AngularJS, which increases the difficulty of AngularJS learning. This tutorial attempts to explain in a popular language.Basic,Most practicalContent,Simplify the learning process and reduce the learning difficultyIs the original intention of this tutorial.

This series of tutorialsTranslationChris SmithOfAngualr BasicsTo provide you with a brief overview, integrate the understanding of the bloggers.Simple and clear.

This article is a series of tutorials, article 4th controller, translated fromControllers.

2. Text

In the previous chapter, I asked you to hold the reins and only use Angular as HTML Function Extension. Of course, Angular is far more than that, in fact, implementing custom behavior through Javascript is a necessary part of every Angular project. If you have the impulse to program in the previous chapter, your patience should be rewarded. Now it's time to write Javascript.

The most common method to add control to an Angular view is through the controller. The simplest way to write a controller is by writing constructor. To help you understand the entire process, we can use a very simple controller to demonstrate it (very simple, even if there is no hello world, it is an empty controller ).

The following is our controller ).

/* empty-controller.js */function EmptyController() {};

Of course, we must import the angular class library and useng-appThe Command tells html that angular is used here.

<! -- Index.html --> <! -- Import the class library --> <script src = "// ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"> </script> <! -- Google is walled and you can use cdn in China --> <script src = "// developer.bdimg.com/libs/angular.js/1.#/angular.min.js"> </script> <! -- Ng-app tells html that angular --> <body ng-app = "app"> <! -- Other examples to be inserted here. --> </body>

Controllers can be defined globally using constructors. This is the method used in this chapter. In versions earlier than Angular1.3, you can directly use the simple method, but now you need to configure it to create a named application module (named application module ). How to Use the Angular module is described in the following modules, dependency injection, and service chapters. Now, you only need to use the following casesBoilerplate)You can.

/* module.js */angular.module('app', []);angular.module('app').config(['$controllerProvider', function($controllerProvider) {  $controllerProvider.allowGlobals();}]);

Now, let's try the noop controller ).

2.1 ng-controller

As usual, you can do this with instructions.ng-controllerThe command can be used to locate and call the controller function.

<!-- empty-controller.html --><p ng-controller="EmptyController"></p>

Of course, as you think, it will call the one we defined aboveEmptyControllerConstructor, nothing to do. Next, let's look at what is a controller? How to use it?

2.2 build a model-Constructing the model

In the core overview section of the official guide, Angular's work is described as "passing variables and function functions to expressions and commands". The function here refers to the callback function. We will explain it later, now let's take a look.Variable InitializationAndModel preparation.

After understanding that the Angular model is some common Javascript code that can be read by the expression scope, preparing the model is meaningless. Common javascript code? Yes, we can write common js Code, so that we can add a string attribute to the empty controller.

/* message-controller-as.js */function MessageController() {  this.message = "This is a model.";}

Easy! Succeeded? Have we successfully created a model? Yes or not?

The answer is almost. When we try to obtain the message attribute in the scope, it is a model. One way to complete this task is to make the entire Controller an attribute in the scope. It sounds very mysterious. when you understand the syntax secrets, everything will become very simple.

2.3 Controller as property name-Controller as propertyName

As described by the official API,ng-controllerAcceptablecontroll as propertyNameExpression as a parameter,Note:This feature can be used only in Versions later than Angular1.2.

<!-- message-controller.html --><p ng-controller="MessageController as controller">  {{controller.message}}</p>

The compilation result is: This is a model.

In this way, we have prepared the model data with the controller.

Although this method of attaching attributes to references is straightforward and clear, "exposing the entire controller to the view" is easy to misunderstand. It makes people feel that the controller is part of the model. In fact, the role of the controller is only to prepare data for the model. When you only meet the requirements of the client and do not consider more requirements, testing and debugging will be very simple. In addition, this method will bring noise to the view code, because all attributes must be accessed through the reference of the controller. View code is usually the most demanding area of web application noise. It may be the first place to encounter difficulties in understanding. Finally, the controller and scope work in parallel. From the teaching point of view, it is very useful to clarify the reference of scope and precisely control it. Through these controls, we can clearly expose the part we want to expose to the view. Therefore, this book prefers this controller style that can clearly manage scope objects.

So the question is, how can we get the reference of this scope object? Use the new operator to create? Or from somewhere?

2.4 Dependency injection-Dependency injection

No. We get it through dependency injection. You may have noticed that I have not displayed the code for instantiating the controller, for examplevar controller=new MessageController();Who created the Controller Used in the view?

Of course it is Angular. Angular is an Inversion of Control (IoC) container that manages the lifecycle of application components. Angular creates a new controller or component. This saves time and, more importantly, allows Angular to inject resources and dependencies to components.

2.4.1 $ scope

As a component managed by the dependency injection framework, the Controller only needs to use the $ scope parameter. The parameter name is critical. In fact, if you compress your Javascript source code, you will destroy the dependency injection mechanism (don't worry, there is a work und, we will explain in the dependency injection chapter ).

/* message-controller-scope.js */function MessageController($scope) {  $scope.message = "This is a model.";}

Add a constructor$scopeParameter, we notify Angualr that we need a reference of the view scope. Can it be simpler? Now we can not declare it in the controller.messageAttribute, but directlyscope.

In the templateng-controllerRemove from commandas controller.controller.messageChangemessageThis is the unique attribute that we attach to the scope.

<!-- message-controller-scope.html --><p ng-controller="MessageController">  {{message}}</p>

The compilation result is: This is a model.

Although both methods work normally, this book uses more specific$scope. Dependency injection is a feature of Angualr, so we should be familiar with it as much as possible.

2.5 Model view controller MVC-Model-view-controller

The Controller definition in the official guide also involves exposing "functionality" to the view ". Before we discuss this issue, I think it is necessary to spend some time discussing the differences between Angular controllers and classic MVC models.

According to the interpretation of model-view-controller (MVC) in Wikipedia, the controller "mediates input, converting it to commands for the model or view ". However, it is difficult to understand "commands for the model or view" in Angular scope, because Angular's MVC model is very simple and uses anemia models with only rules and no logic. Currently, Angular's most popular method is to put all the business logic (domain logic) into the controller. In other words, angular applications tend to lean models and fat controllers (skinny models and fat controllers ).

If you are familiar with the mode, such as the rich domain model, the thin Model Fat Controller (Skinny Controller, Fat model), and so on, I think you will find Angular method a little backward. I think this is only a matter of priority. In client programming, there is a significant difference between the two. One side is declarative, DOM-centric view code, the other side is imperative, data-driven JS Code to process business logic and application basics. This is a huge success, and I'm glad to be concerned with frameworks like Angular. After a while,The business logic is separated from the Controller.It may take a higher priority. We may see thatRicher models).

2.6 Functions-Functions

Let's write a controller that contains a simple function and call this function in the view. You may think that, as we mentioned in the previous chapter, Angular cannot declare functions in the view.

The following Controller specifies an attribute of a function to the scope.

/* count-controller.js */function CountController($scope) {  $scope.count = function() { return 12; }}

There is no difference between calling function methods in expressions and common js Code.{{ }}.

<!--count-controller.html--><p ng-controller="CountController">  There are {{count()}} months in a year.</p>

The compilation result is: There are 12 months in a year.

Note:The function is not simply called and forgotten, but bound to the model. What does it mean? Your Angular binding feature (You may take it for granted) means Angular will not only call this function when the view is rendered for the first time, but also call it when the relevant model changes. To let everyone understand the working principle, we need a function that uses model data. The following sum function uses the model attributes declared in two scopes,operand1Andoperand2. Angular calls functions and rendering results when any attribute changes.

/* addition-controller.js */function AdditionController($scope) {  $scope.operand1 = 0;  $scope.operand2 = 0;  $scope.add = function() {    return $scope.operand1 + $scope.operand2;  }  $scope.options = [0,1,2,3,4];}

Because we have used the input command multiple times, this time let us use the select command of Angular to change the model data. You may have noticed that$scope.options, We will useng-optionsThe Command places the array data in the select statement.x for x in optionsThis statement is a bit nonsense. Remember it anyway ().

<!-- addition-controller.html --><p ng-controller="AdditionController">  <select ng-model="operand1" ng-options="x for x in options"></select>  + <select ng-model="operand2" ng-options="x for x in options"></select>  = {{add()}}</p>

The compiled result is shown in the animation below.

Good! However, if you don't want to use operand1 or operand2 but you want to use properties, we can improve generalization. Get rid of your refactoring manual and pick up your sleeves to abstract parameters.

/* addition-controller-params.js */function AdditionController($scope) {  $scope.number = 2;  $scope.add = function(operand1, operand2) {    return operand1 + operand2;  }}

Within the expression, the function parameter can be an attribute or a literal value.

<!-- addition-controller-params.html --><p ng-controller="AdditionController">  {{add(number, 2)}} is not the same as {{add(number, "2")}}  <br>  2 + 2 + 2 + 2 = {{add(2, add(2, add(2, 2)))}}</p>

The compilation result is:
4 is not the same as 22
2 + 2 + 2 + 2 = 8

Next, we use a callback function to process user behavior.

2.7 callback function

In the previous chapter, we used ng-click to change the boolean value.ng-initInitialize authorized in the command, and useng-click="authorized = !authorizedSimple implementation and intra-row callback. Let's make an improvement in this case and put the model initialization and logic variable switching in the controller.

/* auth-controller.js */function AuthController($scope) {  $scope.authorized = true;  $scope.toggle = function() {    $scope.authorized = !$scope.authorized  };}

NowtoggleIs a function in the scope,ng-clickThe parameter looks like a function call.toggle(). It is not a real function call, but a string that is executed when a user clicks.

<!-- auth-controller.html --><div ng-controller="AuthController">  <p>    The secret code is    <span ng-show="authorized">0123</span>    <span ng-hide="authorized">not for you to see</span>  </p>  <input class="btn btn-xs btn-default" type="button" value="toggle" ng-click="toggle()"></div>

The compilation result is shown in the animation below.

The case still works normally and implements logical switching in a better place. Why is it better? A good question. The advantage of processing user behavior in the controller is that when we implement more complex user behavior, we can ensure that the Code is clear and readable, for example, you can process asynchronous model data from a remote server (if you can't wait to understand this knowledge, jump to the http section of this book ).

2.8 conclusion

In Angular usage, javascript is introduced. controller (controller) is used to prepare data for the view in MVC mode. It declares attributes on the scope object to implement this function. In the next chapter, we will introduce the scope object in detail and learn how to organize it into a system that matches the DOM structure of the application.

3. Statement

Front-end development whqet, focus on front-end development, and share related resources. Wang haiqing, A csdn Expert Blog, hopes to help you. Limited by the author's limited level, it is inevitable to make mistakes. Thank you!
You are welcome to reprint it in any form. Please note the loading and retain the text in this section.
The original Article, http://blog.csdn.net/whqet/article/details/44698845
Welcome to independent blog http://whqet.github.io.

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.