04 Controller-ANGULARJS Basic Tutorial

Source: Internet
Author: User

0. Catalogue

    • Directory
    • Objective
    • Body
      • 1 Ng-controller
      • 2 Building Models-constructing the model
      • 3 Controller as attribute name-controller as PropertyName
      • 4 Dependency Injection-dependency injection
        • Scope
      • 5 Model View Controller Mvc-model-view-controller
      • 6 function-functions
      • 7 Back-tone function
      • 8 Conclusion
    • Statement

1. Preface

Angularjs is designed to overcome the lack of HTML in building applications. HTML is a good declarative language for static text presentation design, but it seems weak to build a Web application, so Angularjs does some work to solve the problem of static Web page technology in the construction of dynamic applications.

Angularjs is designed to simplify web app development , and the essence is simple . However, there are many angularjs tutorials at home and abroad, which focus on Angularjs's strong points, thus increasing the difficulty of angularjs learning, this tutorial tries to explain the most basic and practical content in popular language, The purpose of this tutorial is to simplify the learning process and reduce the difficulty of learning.

This series of tutorials is a summary of the translation of Chris Smith 's angualr Basics , which incorporates the blogger's own understanding and provides a simple and clear learning tutorial for everyone.

This article is a series of tutorial 4th Controller, translated from Controllers.

    1. Order
    2. Introduction-introduction
    3. Basic-basics
    4. Controller-controllers
    5. Scope-scopes
    6. Set-collections
    7. Module-modules
    8. Dependency Injection-dependency Injection
    9. Service-services
    10. Filter-filters
    11. Directive-directives
    12. Instruction Scope-directive Scopes
    13. Routing-routing
    14. Communication-http
    15. Conclusion
2. Text

In the previous chapter, I asked you to take the reins and just extend the angular as HTML, of course angular much more than that, and actually implementing custom behavior through JavaScript is a necessary part of every angular project. If you have the urge to program in the previous chapter, your patience deserves to be rewarded, now it's time to write some JavaScript.

The most common way to add control to angular view is through the controller, the simplest way to write a controller by writing a constructor. To help you understand the whole process, we demonstrate it through a very simple controller (very simple, not even Hello world, just an empty controller).

Here is our controller.

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

Of course, we have to import the angular class library and use the ng-app command to tell HTML that we will use angular here.

<!--index.html --<!--Import class library --<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"> </script><!--google is wall, you can use the domestic cdn--><script src="//apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script><!--Ng-app Tell HTML, we'll use angular--<body Ng-app="App">  <!--Other examples to being inserted here--</body>

The controller can be defined in a global scope using constructors, which is how this is used. The simple way can be used directly in previous versions of Angular1.3, but now requires some configuration to create a named Application module (named Application modules). How to use the angular module is explained in detail in the next modules, Dependency injection and service chapters, and now you just need to use the following case as a template file (boilerplate) .

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

Now let's just ignore that, let's try a controller that doesn't do anything. NoOp controllers.

2.1 Ng-controller

As is often the case with instructions (Directive), the ng-controller command can be used to find and invoke the Controller function by its name.

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

Of course, as you would expect, it will call the constructor that we defined above EmptyController , nothing. Next, let's look at what the controller is. How do I use it?

2.2 Building Models-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 directives", where function functions refer to callback functions, which we'll focus on later, and now we'll look at the initialization of variables and the preparation of the model .

Knowing that the angular model is just plain JavaScript code that can be read by an expression scope, preparing the model is a trivial thing. Common JavaScript code? Yes, we can write the normal JS code, let us add a string property to the empty controller.

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

It's simple! Have you succeeded? Have we successfully created a model? Yes or no?

The answer is almost. When we get the message property in the attempted scope, it is a model. One way to do this is to have the entire controller as a property in scope, which sounds iffy, and when you understand the secret of grammar, everything becomes very simple.

2.3 Controller as attribute name-controller as PropertyName

As the official API describes, ng-controller you can accept controll as propertyName an expression as a parameter, and note that this feature is only available for later versions of Angular1.2.

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

The results of the compilation are: This is a model.

In this way, we are using the controller to prepare the model data.

Although this is straightforward to refer to attached properties, "exposing the entire controller to the view" can be misleading, giving the impression that the controller is part of the model, and in fact, the controller simply prepares the data for the model. Testing and debugging can be very simple when you just meet the client's requirements and don't consider more requirements. Furthermore, this approach brings noise to the view code, because all properties must be accessed through a reference to the controller. The view code is often the most demanding area of a Web application's noise, and it may be the first place to have difficulty understanding after a glimpse. Finally, the Controller and scope (scope) work together, and from a pedagogical standpoint, it is useful to have a clear reference to the scope and fine-grained control of it, and with these controls we can explicitly expose the parts of the view that we want to expose. Therefore, this book prefers the controller style that explicitly manages scope objects.

So here's the question, how do we get a reference to this scope object? Use the new operator to build one? Or is it a request from somewhere?

2.4 Dependency Injection-dependency Injection

No. We get it through dependency injection. You may have noticed that I did not show the code that instantiates the controller, for example var controller=new MessageController(); , who created the controller used in the view?

Of course it's angular. Angular is a control reversal (inversion of control, abbreviation for IOC) container that can manage the lifetime of the application component. When a new controller or a new component is needed, angular creates one. This can save time and, more importantly, allow angular to inject resources, dependencies, etc. into components.

2.4.1 $scope

As a component that is managed through a dependency injection framework, the controller needs only one parameter $scope. The name of the parameter is very critical, in fact, if you compress your JavaScript source code, you will break the dependency injection mechanism (there is no need to worry, there is a workaround, we will explain in the Dependency Injection section).

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

By adding $scope parameters to the constructor, we inform ANGUALR that we need a reference to the scope of the view. Could it be a little simpler? Now we can not declare the attribute in the controller message , but scope define it directly in.

In the template, we remove it from the ng-controller Directive as controller . controller.messagebecomes message , this is the only property that we attach to scope.

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

The results of the compilation are: This is a model.

Although both methods work correctly, the book is used in a more specific $scope way. Dependency Injection is a feature of angualr, so we should be as familiar with it as possible.

2.5 Model View Controller Mvc-model-view-controller

The controller definition of the official guide also involves exposing "functionality" to the view. Before we discuss this issue, I think it is necessary to take some time to discuss the difference between the angular controller and the classic MVC pattern.

According to the Wikipedia Model-view-controller (MVC) explanation, the controller "mediates input, converting it to commands for the model or view". However, it is difficult to understand the "commands for the model or view" in the angular range, because the angular MVC model is very simple, using only the rules and no logic of the anemia model. Up to now, angular's most popular approach is to put all of 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 patterns such as the rich domain model, the Lean Model Fat Controller (Skinny controller, fat model), etc., I think you will find that the angular method is a bit backwards. I think this can only be a priority problem, 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 handle business logic and application Foundation. This is a huge success, and I'm happy to look at these frameworks like angular. After a while, the business logic separating from the controller can take on higher priority, and we may see a trend of rich models (richer models) .

2.6 Function-functions

Let's write a controller that contains a simple function and experience the call to that function in the view. As you may recall, in the previous chapter we said that angular does not allow the declaration of functions in a view.

The following controller assigns a function to a property of scope.

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

There is no difference between calling a function method and ordinary JS code in an expression {{ }} .

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

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

Note that the function is not simply called and forgotten, but is tied to the model. What do you mean? Your angular binding feature (which you might take for granted) means that angular not only invokes the function when the view is first rendered, but also when the relevant model changes. To get everyone to understand how it works, we need a function that uses the model data, and the SUM function below uses the model attributes declared in two scopes, operand1 and operand2 . Angular will invoke the function and render the result when any property has changed.

/* 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 ];}  

Since we have used the input directive several times, let's change the model data with angular's Select command. You may have noticed the $scope. Options for the last line of the code above, and we will then use the ng-options directive to place the array data in the Select. x for x in Options This is a bit of crap, so remember it anyway ().

<!--addition-controller.html-->  <p  ng-controller  =  "Additioncontroller" ;  < select  ng-model  = "Operand1"  ng-options  = "x for x in Options" ;  Span class= "Hljs-tag" ></select ;  + <select  ng-model  = " Operand2 " ng-options  =" x for x in Options " ;  </select ;  = {{add()}}</P>

After compiling the results are shown in the following diagram.

That's good! However, if you do not want to use OPERAND1 and operand2, we can make some improvements in generalization. Get rid of your refactoring manual and roll up your sleeves to make some parameter abstractions.

/* addition-controller-params.js */function AdditionController($scope) {  $scope2;  $scopefunction(operand1, operand2) {    return operand1 + operand2;  }}

Inside an expression, a function parameter can be either a property 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 result of the compilation is:
4 is not the same as 22
2 + 2 + 2 + 2 = 8

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

2.7 Callback function

In the previous chapter there was a case, using Ng-click to toggle the Boolean value, initialize the authorized in the ng-init instruction, make use of ng-click="authorized = !authorized the implementation of simple, in-line callback, let us make an improvement of the case, the model initialization, switching logic variables are placed in the controller.

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

Now it toggle 's a function in a scope, and ng-click the arguments look like a function call toggle() . It is not a real function call, just a string that executes 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 the See</span>  </P>  <input class="btn btn-xs btn-default" type="button" value ="Toggle" ng-click="Toggle ()"></div>

The compilation results are shown in the following motion diagram.

The case is still working, and a logical switchover is implemented in a better place. Why is it better? A very good question. The benefit of handling user behavior within a controller is that when we implement more complex user behavior, we can ensure that the code is legible, such as processing asynchronous model data from a remote server (if you can't wait to know this, skip to the HTTP section of the book).

2.8 Conclusion

In the use of angular, we introduced JavaScript, a controller that plays in the MVC pattern to prepare the data for the view, which is implemented by declaring properties on the scope object. In the next chapter, we'll cover the scope object in detail to see how it's organized into a system that matches the DOM structure of the application.

3. Disclaimer

Front-end development whqet, focus on front-end development, share related resources. CSDN Expert blog, Wang Haiqing hope to help you, limited to the author level limited, error inevitably, welcome to shoot Bricks!
Welcome any kind of reprint, please indicate loading, keep this paragraph text.
This article is linked in the original, http://blog.csdn.net/whqet/article/details/44698845
You are welcome to visit the Independent blog Http://whqet.github.io

04 Controller-ANGULARJS Basic Tutorial

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.