AngularJS syntax explanation (continued) and angularjs syntax explanation

Source: Internet
Author: User

AngularJS syntax explanation (continued) and angularjs syntax explanation

Src and href attributes

In Angularjs, src should be written as ng-src, and href should be written as ng-href, for example:

Copy codeThe Code is as follows:

<A ng-href = "/shop/category = {number}"> Some text </a>

Expression

In the template, you can perform simple mathematical operations, comparison operations, Boolean operations, bit operations, referenced arrays, and object symbols. Although we can use expressions to do many things, however, expressions are executed using a custom interpreter (part of Angular), rather than using Javascript to execute eval () functions, so the limitations are great.
Although the expressions here are more rigorous than Javascript expressions, they have better fault tolerance for undefined and null. If an error occurs, the template simply does not display anything, instead of throwing an NullPointerException error. For example:

Copy codeThe Code is as follows:
<Div ng-controller = 'somecontroller'>
<Div >{{ computer ()/10 }}</div> // although it is legal, it puts the business logic in the template. Avoid this practice.
</Div>

Differentiate UI and controller responsibilities

Controllers are bound to specific DOM fragments, which are the content they need to manage. There are two main ways to associate the controller to a DOM node, one is to declare in the template through ng-controller, the second is to bind it to a Dynamically Loaded DOM template fragment through a route. This template is called a view. We can create nested controllers. They can share data models and functions by inheriting the number structure. Real nesting occurs on the $ scope object through the internal original inheritance mechanism, $ scope of the parent controller object is passed to the nested $ scope (all attributes, including functions ). For example:

Copy codeThe Code is as follows:
<Div ng-controller = "ParentController">
<Div ng-controller = "ChildController">... </div>
</Div>

Use $ scope to expose model data

The $ scope attribute is displayed, for example, $ scope. count = 5. You can also create a data model through the template.

By expression. For example

Copy codeThe Code is as follows:
<Button ng-click = 'count = 3'> Set count to three </button>

Use ng-model on Form Items

Similar to expressions, the model parameters specified on ng-model also work in the outer controller. The only difference is that it establishes a bidirectional binding relationship between the form item and the specified model.

Monitor Data Model changes with watch

$ Watch function Signature: $ watch (watchFn, watchAction, deepWatch)
WatchFn is a string with an Angular expression or function. It returns the current value of the monitored data model. WatchAction is a function or expression that is called when watchFn changes. The function signature is:
Function (newValue, oldValue, scope) deepWatch if it is set to true, this optional Boolean parameter will command Angular to check whether every attribute of the Monitored object has changed. You can use this parameter if you want to monitor elements in an array or all attributes of an object instead of a simple value. Note: Angular needs to traverse arrays or objects. If the set is large, the calculation will be more complex.

$ Watch function returns a function. When you do not need to receive a change notification, you can use this function to log out of the monitor.
If we need to monitor a property and then cancel monitoring, we can use the following code: var dereg = $ scope. $ watch ('somemodel. someproperties', callbackOnChange ());
... Dereg ();

The instance code is as follows:

Copy codeThe Code is as follows:
<Html ng-app>
<Head>
<Title> Your Shopping Cart </title>
<Script type = "text/javascript">
Function CartController ($ scope ){
$ Scope. bill = {};
$ Scope. items = [
{Title: 'paint pots', quantity: 8, price: 3.95 },
{Title: 'polka dots', quantity: 17, price: 12.95 },
{Title: 'pebbles ', quantity: 5, price: 6.95}
];
$ Scope. totalCart = function (){
Var total = 0;
For (var I = 0, len = $ scope. items. length; I <len; I ++ ){
Total = total + $ scope. items [I]. price * $ scope. items [I]. quantity;
}
Return total;
}
$ Scope. subtotal = function (){
Return $ scope. totalCart ()-$ scope. bill. discount;
}
Function calculateDiscount (newValue, oldValue, scope ){
$ Scope. bill. discount = maid> 100? 10: 0;
} // The watchAction function here
$ Scope. $ watch ($ scope. totalCart, calculateDiscount); // The watch function here
}
</Script>
</Head>
<Body>
<Div ng-controller = "CartController">
<Div ng-repeat = 'item in items '>
<Span >{{ item. title }}</span>
<Input ng-model = 'item. quantity '>
<Span >{{ item. price | currency }}</span>
<Span >{{ item. price * item. quantity | currency }}</span>
</Div>
<Div> Total :{{ totalCart () | currency }}</div>
<Div> Discount: {bill. discount | currency }}</div>
<Div> SubTotal :{{ subtotal () | currency }}</div>
</Div>
<Script type = "text/javascript" src = "angular. min. js"> </script>
</Body>
</Html>

The above watch has a performance problem. The calculateTotals function has been executed six times, three of which are due to cycle failure. Data will be re-rendered for each loop.
The improved code is as follows:

Copy codeThe Code is as follows:
<Html ng-app>
<Head>
<Title> Your Shopping Cart </title>
<Script type = "text/javascript">
Function CartController ($ scope ){
$ Scope. bill = {};
$ Scope. items = [
{Title: 'paint pots', quantity: 8, price: 3.95 },
{Title: 'polka dots', quantity: 17, price: 12.95 },
{Title: 'pebbles ', quantity: 5, price: 6.95}
];
Var totalCart = function (){
Var total = 0;
For (var I = 0, len = $ scope. items. length; I <len; I ++ ){
Total = total + $ scope. items [I]. price * $ scope. items [I]. quantity;
}
$ Scope. bill. totalcart = total;
$ Scope. bill. discount = total> 100? 10: 0;
$ Scope. bill. subtotal = total-$ scope. bill. discount;
}
$ Scope. $ watch ('items ', totalCart, true); // only watch the changes of items.
}
</Script>
</Head>
<Body>
<Div ng-controller = "CartController">
<Div ng-repeat = 'item in items '>
<Span >{{ item. title }}</span>
<Input ng-model = 'item. quantity '>
<Span >{{ item. price | currency }}</span>
<Span >{{ item. price * item. quantity | currency }}</span>
</Div>
<Div> Total :{{ bill. totalcart | currency }}</div>
<Div> Discount: {bill. discount | currency }}</div>
<Div> SubTotal: {bill. subtotal | currency }}</div>
</Div>
<Script type = "text/javascript" src = "angular. min. js"> </script>
</Body>
</Html>

For large itms arrays, if you only re-calculate the bill attribute each time you display the page in Angular, the performance will be much better. You can implement this by creating a $ watch function with watchFn.

Copy codeThe Code is as follows:
$ Scope. $ watch (
Var totalCart = function (){
Var total = 0;
For (var I = 0, len = $ scope. items. length; I <len; I ++ ){
Total = total + $ scope. items [I]. price * $ scope. items [I]. quantity;
}
$ Scope. bill. totalcart = total;
$ Scope. bill. discount = total> 100? 10: 0;
$ Scope. bill. subtotal = total-$ scope. bill. discount;
});

Monitor multiple things

If you want to monitor multiple attributes or objects and execute a function when any of them changes, you have two basic options:

Value after monitoring connects these attributes

Put them in an array or object and pass a value to the deepWAtch parameter.

Description:
In the first case, if there is a things object in your scope, it has two attributes a and B. When these two attributes change, you need to execute the callMe () function, you can monitor both attributes $ scope. $ watch ('things. a + things. B ', callMe (...));
When the list is very long, you need to write a function to return the value after the connection.

In the second case, you need to monitor all attributes of the things object. You can do this:

Copy codeThe Code is as follows:
$ Scope. $ watch ('things ', callMe (...), true );

Use module to organize Dependencies

Provider (name, Object OR constructor () Description: it is complicated to create a configurable service. If you pass an Object as a parameter, the Object must contain a function named $ get. This function must return the service name. Otherwise, angularjs will assume that you are passing a constructor. Calling constructor will return the service instance object.
Factory (name, $ get Function () indicates that the creation logic of a service that cannot be configured is complex. You need to specify a function. When calling this function, the service instance is returned. It can be viewed as provider (name, {$ get: $ getFunction.
Service (name, constructor () is an unconfigurable service, and the Creation logic is relatively simple. Similar to the constructor parameter of the provider function above, Angular can call it to create a service instance.

Example of using module factory

Copy codeThe Code is as follows:
<Html ng-app = 'shoppingmodule '>
<Head>
<Title> Your Shopping Cart </title>
<Script type = "text/javascript" src = "angular. min. js"> </script>
<Script type = "text/javascript">
Var ShoppingModule = angular. module ('shoppingmodule', []);
ShoppingModule. factory ('items ', function (){
Var items = {};
Items. query = function (){
Return [
{Title: 'paint pots', description: 'ots full of paint', price: 3.95 },
{Title: 'paint pots', description: 'ots full of paint', price: 3.95 },
{Title: 'paint pots', description: 'ots full of paint', price: 3.95}
];
};
Return items;
});
Function ShoppingController ($ scope, Items ){
$ Scope. items = Items. query ();
}
</Script>
</Head>
<Body ng-controller = 'shoppingcontroller'>
<H1> Shop !! </H1>
<Table>
<Tr ng-repeat = 'item in items '>
<Td >{{ item. title }}</td>
<Td >{{ item. description }}</td>
<Td >{{ item. price | currency }}</td>
</Tr>
</Table>
</Body>
</Html>

Introduce third-party modules

In most applications, you can create a single module for all code and put all dependent items into this module. This will work well. However, if you plan to use the services or commands provided by third-party packages, they generally have their own modules. You need to define dependency concerns in the application module to reference them. For example:
Var appMod = angular. module ('app', ['snapshot', 'super']);

Filter Example

Copy codeThe Code is as follows:
<Html ng-app = 'shoppingmodule '>
<Head>
<Title> Your Shopping Cart </title>
<Script type = "text/javascript" src = "angular. min. js"> </script>
<Script type = "text/javascript">
Var ShoppingModule = angular. module ('shoppingmodule', []);
ShoppingModule. filter ('titlecase', function (){
Var titleCaseFilter = function (input ){
Var words = input. split ('');
For (var I = 0; I <words. length; I ++ ){
Words [I] = words [0]. charAt (0). toUpperCase () + words [I]. slice (1 );
}
Return words. join ('');
};
Return titleCaseFilter;
});
Function ShoppingController ($ scope ){
$ Scope. pageHeading = 'this is a test case ';
}
</Script>
</Head>
<Body ng-controller = 'shoppingcontroller'>
<H1 >{{ pageHeading | titleCase }}</Body>
</Html>

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.