Home  >  Article  >  Web Front-end  >  Detailed explanation of AngularJS syntax (continued)_AngularJS

Detailed explanation of AngularJS syntax (continued)_AngularJS

WBOY
WBOYOriginal
2016-05-16 16:18:13936browse

src and href attributes

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

Copy code The code is as follows:

Expression

You can perform simple mathematical operations, comparison operations, Boolean operations, bitwise operations, reference arrays, object notations, etc. in templates. Although we can do many things with expressions, expressions use a custom interpreter. It is executed (part of Angular) instead of using Javascript's eval() function, so it has greater limitations.
Although expressions here are more strict than Javascript in many ways, they are more tolerant of undefined and null. If an error is encountered, the template simply displays nothing instead of throwing a NullPointerException error. For example:

Copy code The code is as follows:


{{computer() /10 }}
//Although it is legal, it puts the business logic into the template. This approach should be avoided

Separate the responsibilities of UI and controller

Controllers are bound to specific DOM fragments, and these fragments are the content they need to manage. There are two main ways to associate a controller to a DOM node. One is to declare it in the template through ng-controller. The second is to bind it to a dynamically loaded DOM template fragment through routing. This template is called view. We can create nested controllers. They can share data models and functions through inheritance structures. The real nesting occurs on the $scope object. Through the internal primitive inheritance mechanism, the $scope of the parent controller object will be passed to the inner nested $scope (all properties, including functions). For example:

Copy code The code is as follows:


...


Use $scope to expose model data

You can create $scope properties explicitly, for example $scope.count = 5. You can also create data models indirectly through the template itself.

By expression. For example

Copy code The code is as follows:


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 this creates a two-way binding between the form item and the specified model.

Use watch to monitor changes in the data model

The function signature of $watch is: $watch(watchFn,watchAction,deepWatch)
watchFn is a string with an Angular expression or function that returns the current value of the monitored data model. watchAction is a function or expression that is called when watchFn changes. Its function signature is:
function(newValue,oldValue,scope) deepWatch If set to true, this optional Boolean parameter will instruct Angular to check whether each property of the monitored object has changed. You can use this parameter if you want to monitor elements in an array, or all properties on an object, rather than monitoring a single value. Note that Angular needs to traverse arrays or objects. If the collection is large, the operation will be complicated and heavy.

The $watch function will return a function. When you do not need to receive change notifications, you can use this returned function to log out of the monitor.
If we need to monitor a property and then log out of the monitoring, we can use the following code: var dereg = $scope.$watch('someModel.someProperty',callbackOnChange());
... dereg();

The example code is as follows:

Copy code The code is as follows:



    Your Shopping Cart
   


   

       

            {{item.title}}
           
            {{item.price | currency}}
            {{item.price * item.quantity | currency}}
       

       
Total: {{totalCart()| currency }}

       
Discount: {{bill.discount | currency}}

       
SubTotal: {{subtotal() | currency}}

   

   


上面的watch存在性能问题,calculateTotals函数执行了6次,其中三次是因为循坏,每次循环,都会重新渲染数据。
下面是改良后的代码

复制代码 代码如下:



    Your Shopping Cart
   


   

       

            {{item.title}}
           
            {{item.price | currency}}
            {{item.price * item.quantity | currency}}
       

       
Total: {{bill.totalcart| currency }}

       
Discount: {{bill.discount | currency}}

       
SubTotal: {{bill.subtotal | currency}}

   

   


对于大型的itms数组来说,如果每次在Angular显示页面时只重新计算bill属性,那么性能会好很多。通过创建一个带有watchFn的$watch函数,我们可以实现这一点。

复制代码 代码如下:

$scope.$watch(
var totalCart = function() {
            var total = 0;
for (var i=0,len=$scope.items.length;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 properties or objects and execute a function when any of them changes, you have two basic options:

Monitor the value of concatenating these properties

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

Instructions respectively:
In the first case, if there is a things object in your scope, it has two properties a and b. When these two properties change, the callMe() function needs to be executed. You can monitor these two at the same time. properties $scope.$watch('things.a things.b',callMe(...));
When the list is very long, you need to write a function to return the concatenated value.

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

Copy code The code is as follows:

$scope.$watch('things',callMe(...),true);

Use modules to organize dependencies

provider(name,Object OR constructor()) Description: A configurable service that creates complex logic comparisons. If you pass an Object as a parameter, then the Object object must have a function named $get, which needs to return the name of the service. Otherwise, angularjs will think that what you pass is a constructor, and calling the constructor will return the service instance object.
factory(name,$get Function()) Description: A non-configurable service, the creation logic is relatively complicated. You need to specify a function that, when called, will return the service instance. It can be seen as provider(name,{$get:$getFunction()}).
service(name,constructor()) A non-configurable service, creating logic is relatively simple. Similar to the constructor parameter of the provider function above, Angular can create a service instance by calling it.

Example of using module factory

Copy code The code is as follows:



Your Shopping Cart




Shop!!



   
       
       
       
   
{{item.title}}{{item.description}}{{item.price | currency}}



引入第三方模块

在大多数应用中,创建供所有代码使用的单个模块,并把所有依赖的东西放入这个模块中,这样就会工作的很好。但是,如果你打算使用第三方包提供的服务或者指令,他们一般都带有自己的模块,你需要在应用模块中定义依赖关心才能引用他们。 例如:
var appMod = angular.module('app',['Snazzy','Super']);

关于filter的例子

复制代码 代码如下:



Your Shopping Cart




{{pageHeading | titleCase}}




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn