Home Web Front-end JS Tutorial Detailed explanation of AngularJS syntax (continued)_AngularJS

Detailed explanation of AngularJS syntax (continued)_AngularJS

May 16, 2016 pm 04:18 PM
angularjs grammar

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
How to quickly turn your Python code into an API How to quickly turn your Python code into an API Apr 14, 2023 pm 06:28 PM

When it comes to API development, you may think of DjangoRESTFramework, Flask, and FastAPI. Yes, they can be used to write APIs. However, the framework shared today allows you to convert existing functions into APIs faster. It is Sanic . Introduction to Sanic Sanic[1] is a Python3.7+ web server and web framework designed to improve performance. It allows the use of the async/await syntax added in Python 3.5, which can effectively avoid blocking and improve response speed. Sanic is committed to providing a simple and fast way to create and launch

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

What are the syntax and structure characteristics of lambda expressions? What are the syntax and structure characteristics of lambda expressions? Apr 25, 2024 pm 01:12 PM

Lambda expression is an anonymous function without a name, and its syntax is: (parameter_list)->expression. They feature anonymity, diversity, currying, and closure. In practical applications, Lambda expressions can be used to define functions concisely, such as the summation function sum_lambda=lambdax,y:x+y, and apply the map() function to the list to perform the summation operation.

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

New type alias syntax in PHP8.0 New type alias syntax in PHP8.0 May 14, 2023 pm 02:21 PM

With the release of PHP 8.0, a new type alias syntax has been added, making it easier to use custom types. In this article, we'll take a closer look at this new syntax and its impact on developers. What is a type alias? In PHP, a type alias is essentially a variable that references the name of another type. This variable can be used like any other type and declared anywhere in the code. The main function of this syntax is to define custom aliases for commonly used types, making the code easier to read and understand.

Parent class calling syntax in PHP8.0 Parent class calling syntax in PHP8.0 May 14, 2023 pm 01:00 PM

PHP is a server-side scripting language widely used in Web development, and PHP8.0 version introduces a new parent class calling syntax to make object-oriented programming more convenient and concise. In PHP, we can create a parent class and one or more subclasses through inheritance. Subclasses can inherit the properties and methods of the parent class, and can modify or extend their functionality by overriding the methods of the parent class. In ordinary PHP inheritance, if we want to call the method of the parent class in the subclass, we need to use the parent keyword to refer to the parent

The connection and difference between Go language and JS The connection and difference between Go language and JS Mar 29, 2024 am 11:15 AM

The connection and difference between Go language and JS Go language (also known as Golang) and JavaScript (JS) are currently popular programming languages. They are related in some aspects and have obvious differences in other aspects. This article will explore the connections and differences between the Go language and JavaScript, and provide specific code examples to help readers better understand these two programming languages. Connection: Both Go language and JavaScript are cross-platform and can run on different operating systems.

What is the difference between C and C++? What is the difference between C and C++? Aug 29, 2023 pm 11:53 PM

The C programming language C is a general-purpose, high-level language originally developed by Dennis M. Ritchie at Bell Labs to develop the UNIX operating system. C was first implemented in 1972 on the DECPDP-11 computer. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. The UNIX operating system, C compiler, and almost all UNIX applications are written in C. For various reasons, C language has now become a widely used professional language. It is a structured language that is easy to learn, it produces efficient programs, it can handle low-level activities, and it can run on a variety of computers.

See all articles