Angular study (i)--Overview

Source: Internet
Author: User

1. Article Summary
This article mainly through a few small examples of the common components of angular simple introduction

2. Data binding
The following is a simple example of calculating total with quantity and costs

<div ng-app ng-init="qty=1;cost=2">    <b>Invoice:</b>    <div>Quantity:<input type="number" min="0" ng-model="Qty" >    </div>    <div>Costs:<input type="number" min="0" ng-model= "Cost">    </div>    <div>        <b>Total:</b> {{qty *  Cost | currency}} </div></div>     

Output results

The following describes how this code works, this code looks like a regular HTML file with some new markup, in angular, such a file is called template, when angular run, it will parse from this template to deal with these new tags, and loaded, transformed, and rendered in the form of a DOM.

The first type of tag is called directives in angular, and they add special functionality to some attributes or elements, such as the Ng-app attribute above, angular recognizes that it is automatically initialized to angular applications. Angular also adds some extended functionality to the input element, such as the next Ng-model, which can store the value of input in a variable, or assign the value of a variable to input, which is a binding of live, one that changes with the other, Called Two-way binding.

The second type of tag is {{expression | filter}} with double curly braces, and when angular's compiler encounters this tag, it replaces the token with the final value of the expression. The expression in the template is a class-javascript variable that angular can read and write to. It should be noted that these variables are not global variables, just like variables in JavaScript functions. Angular gives these variables the concept of scope, so that they can be accessed in the form of model in other parts of the document. For this example, angular's understanding of these directives is to take out the values of the two input boxes and multiply them.

The above example also contains a Filter,filter function is to show the value of the expression to the user, in this case currency filter will eventually convert the value to the currency format output

3. Page logic: Controllers
Let's add some logic that can be entered in different currencies to calculate and pay for this manifest.
Index.html

<div Ng-app="Invoice1" ng-controller="Invoicecontroller as Invoice" >  <b>Invoice:</b>  <div>Quantity:<input type="number" min="0" ng-model= "Invoice.qty" Required >  </div>  <div>Costs:<input type="number" min="0" ng-model=" Invoice.cost " required >    <Select ng-model="Invoice.incurr">      <option ng-repeat="C in Invoice.currencies">{{c}} </option></Select></div>< Div><b>total:</b><span  ng-repeat="C in Invoice.currencies">                       {{invoice.total(c) | currency:c}} </span><button class="btn" ng-click=" Invoice.pay () ">pay</button></div></ Div>           

Invoice1.js

Angular.module (' Invoice1 ', []). Controller (' Invoicecontroller ', function() {   This. Qty =1; This. Cost =2; This. InCurr =' EUR '; This. Currencies = [' USD ',' EUR ',' CNY ']; This. usdtoforeignrates = {USD:1, EUR:0.74, CNY:6.09}; This. Total = function total(Outcurr) {    return  This. ConvertCurrency ( This. Qty * This. Cost, This. InCurr, Outcurr); }; This. convertcurrency = function convertcurrency(amount, InCurr, Outcurr) {    returnAmount * This. Usdtoforeignrates[outcurr]/ This. Usdtoforeignrates[incurr]; }; This. Pay = function pay() {Window.alert ("thanks!"); };});

Output

A controller is included in the JavaScript file, which specifically contains a constructor function that creates a real controller instance. The role of a controller is to expose variables and functions to expressions and directives.

In addition to a JavaScript file that contains a controller, a Ng-controller directive is added to the HTML. This directive (Invoicecontroller) tells Angular that it is responsible for all the child elements under the elements and elements of the directive. Invoicecontroller as invoice this syntax is to tell angular to instantiate the Invoicecontroller controller and save it in the invoice variable in the current scope.

We also modified the variables in all the expressions in the page to give them the prefix of the invoice (Controller instance). The currency that may be selected is defined and initialized in the controller, and is added to the HTML by means of ng-repeat. As with the total function defined in the controller, we can also put {{invoice.total (...)}} bound to HTML.

We also return the Pay button via Ng-click directive to add a click event, and once clicked, a corresponding expression pops up.

4. Business logic: Services
Now, Invoicecontroller contains all the logic for this example. When the program needs to expand, there is a better way is to extract the business logic from the page logic controller to form a service, and service can be reused by other modules, layered thinking in the angular of a embodiment. If you need to change the data, you only need to change it in the service.

Finance2.js

Angular.module (' Finance ', []). Factory (' Currencyconverter ', function() {  varCurrencies = [' USD ',' EUR ',' CNY '];varUsdtoforeignrates = {USD:1, EUR:0.74, CNY:6.09};varconvert = function (amount, InCurr, Outcurr) {    returnAmount * Usdtoforeignrates[outcurr]/usdtoforeignrates[incurr]; };return{currencies:currencies, convert:convert};});

Invoice2.js

Angular.module (' Invoice ', [' Finance ']). Controller (' Invoicecontroller ', [' Currencyconverter ', function(currencyconverter) {   This. Qty =1; This. Cost =2; This. InCurr =' EUR '; This. currencies = Currencyconverter.currencies; This. Total = function total(Outcurr) {    returnCurrencyconverter.convert ( This. Qty * This. Cost, This. InCurr, Outcurr); }; This. Pay = function pay() {Window.alert ("thanks!"); };}]);

First, move the convertcurrency function and the currencies array to the Finance2.js file, but how can the controller get access to the functions in the Finance2?

This is where Dependency injection comes in handy, Dependency injection (DI) is a software design pattern that mainly deals with the creation of objects and functions and how to get those dependencies, angular everything (directives, filters, controllers, services, ... ) can be created and connected via dependency injection. In angular, such a DI container is called injector.

In order to use DI, you need a place where everything is registered. In the angular, this is what modules did. When angular is started, it uses the configuration of the module with the name defined in Ng-app directive, and uses the configuration of all the module that the module needs to rely on.

In the example above, the template contains a directive ng-app= "invoice", which tells angular to use invoice as the main module for this application, the code snippet Angular.module (' Invoice ', [' Finance ']) indicates that the invoice module relies on Finace module,angular using Invoicecontroller and Currencyconverter service.

How does Invoicecontroller get a reference to the Currencyconverter function? In angular, it is very simple, it is defined in the parameters of the constructor function. Injector can create objects in the order in which they are fought, and they can pass previously created objects into the constructor of their dependent objects. In my mother's case, the Invoicecontroller constructor has a parameter called Currencyconverter. This angularj knows the dependencies between the controller and the service.

Finally, the service transfer function is given to the controller as an array, the first of which is the agreed name between the controller and the service dependency, and the second is the name that is actually used in the service. If you learn that spring should be easy to understand, it's easier to make changes to your code, just change the code you're relying on, and it's common in JavaScript, because JavaScript is often compressed into a. B. c. Such a code.

Angular study (i)--Overview

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.