AngularJS makes the shopping cart select all inverse function
This time I will bring you AngularJS How to create a shopping cart select-all and reverse-select function. What are the precautions for AngularJS to create a shopping cart select-all and reverse-select function, as follows. This is a practical case, let’s take a look at it.
I just learned angularJS, so I practiced writing a function similar to the select all/unselect all of the shopping cart. The main functions implemented are:
1. Check the Select All checkbox and all the list data will be checked. Same as canceling, use ng-model to achieve two-way binding;
2. Select all checkboxes in the list, and all of them will be checked; (The method I think of here is to add a checked field to each object, and then check it to trigger the echoChange() function, and use a cc variable to calculate the current checked value as The number of true, and then determine whether the number of checked items is equal to the length of the array. If equal, it proves that all are checked, so the select all button is also assigned a value of true; Is there a simpler way? Please leave a message? Me, thank you! )
3. After all are checked, as long as you cancel an all-selected check status, the check status will be false;
4. Realize the calculation of the subtotal and total amount of the shopping cart, and only calculate the checked products;
There are problems that need to be improved:
1. I used type="number" for the quantity and set min=10, but there is no limit on the value entered manually, so there will be illegal values if entered manually;
2. To delete the product function, I simply used the pop() method to remove the last array element. In fact, each product object should be deleted;
3. There should be a more rigorous method for selecting/unselecting all, which needs to be improved;
Attached code:
<!DOCTYPE html> <htmllang="en"ng-app="testMo"> <head> <metacharset="UTF-8"> <title></title> <linkrel="stylesheet"href="css/bootstrap.css"rel="external nofollow"> <style> .p1{ margin: 20px; } </style> </head> <body> <png-controller="testCtrl"class="p1"> <h4 id="angularJS-购物车实现全选-取消全选">angularJS--购物车实现全选/取消全选</h4> <buttontype="button"class="btn btn-info"ng-click="addProduct()">添加商品</button> <buttontype="button"class="btn btn-danger"ng-click="deleteProduct()">删除商品</button> <br><br> <tableclass="table table-bordered table-responsive"> <thead> <td>操作</td> <td>check状态</td> <td>商品名称</td> <td>单价</td> <td>数量</td> <td>小计</td> </thead> <trng-repeat="p in cart"> <td><inputtype="checkbox"ng-checked="p.checked"ng-click="echoChange(p.id,p.checked,selectAll)"></td> <td>{{p.checked}}||{{p.checked}}</td> <td>{{p.name}}</td> <td>单价:¥{{p.price}}</td> <td>数量:<inputtype="number"ng-model="p.count"min="0"value="p.count"></td> <td>小计:¥{{p.sum}}</td> </tr> </table> <br> <inputtype="checkbox"ng-model="selectAll"ng-click="selectAllClick(selectAll)"><spanng-hide="selectAll">全选</span><spanng-show="selectAll">取消全选</span> <br><br> 已选择<span>{{jishuqi}}</span>件商品,总金额:<span>¥{{ sumTotal }}</span> </p> <scriptsrc="js/angular.js"></script> <script> angular.module('testMo',['ng']).controller('testCtrl',function($scope){ // $scope.p1=new Object(); // $scope.p1.price=10; // $scope.p1.count=1; //购物车应该是一个数组 $scope.selectAll=false;//全选默认为false $scope.cart=[{id:0,name:'商品0',price:10,count:5,sum:10,checked:false}]; $scope.addProduct= function (){ var p=new Object(); p.id=$scope.cart.length; p.name='商品'+ p.id p.price=Math.floor(Math.random()*100);//对数值向下取整 p.count=1; p.sum= p.price* p.count; p.checked=false; $scope.cart.push({id: p.id,name: p.name,price:p.price,count: p.count,sum: p.sum,checked: p.checked}); console.log($scope.cart); } //删除商品 $scope.deleteProduct= function (){ $scope.cart.pop();//删除数组中的最后的一个元素,并且返回这个元素,会改变数组里的元素 } //全选按钮check的点击事件 $scope.selectAllClick= function (sa) { for(var i=0;i<$scope.cart.length;i++){ $scope.cart[i].checked=sa; } } //单个数据的check事件 $scope.echoChange=function(id,ch,se){ $scope.cart[id].checked=!ch; //当所有都选中时,全选也要被勾选 var cc=0;//计算当前数组中checked为真的数目 for(var i=0;i<$scope.cart.length;i++){ // if($scope.cart[i].checked==true){ // cc++; // } $scope.cart[i].checked?cc++:cc; } $scope.selectAll=(cc==$scope.cart.length);//当为真的数目=数组长度时,证明全部勾选 // console.log($scope.selectAll); } //监控数据 $scope.$watch('cart',function(newValue,oldValue,scope){ $scope.sumTotal=0; //总计 $scope.jishuqi=0; //计数器 for(var i in newValue) { var sumN = newValue[i].count * newValue[i].price; //计算出新的结果 $scope.cart[i].sum = sumN.toFixed(2); //保留两位小数并且把它赋值给元数据; if (newValue[i].checked) { $scope.sumTotal += sumN; $scope.jishuqi++; // console.log($scope.sumTotal); // console.log($scope.jishuqi); } } },true); /*$watch简介:在digest执行时,如果watch观察的的value与上一次执行时不一样时,就会被触发。 AngularJS内部的watch实现了页面随model的及时更新。 $watch方法在用的时候主要是手动的监听一个对象,但对象发生变化时触发某个事件。 $watch(watchFn,watchAction,deepWatch); 如果不加第三个参数,那么只会监听cart数组,只有当cart引用改变时才会触发,因此当需要监听一些引用对象时需要把第三个参数设置成true。 */ }); </script> </body> </html>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
JS implements data validation and check box form submission
vue.js two-way binding use Detailed explanation
How to convert numbers and strings into each other in JS
The above is the detailed content of AngularJS makes the shopping cart select all inverse function. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.

SublimeText3 Mac version
God-level code editing software (SublimeText3)