search
HomeWeb Front-endJS TutorialDetailed explanation of AngularJS syntax (continued)_AngularJS

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor