search
HomeWeb Front-endJS TutorialAngularJS implementation of shopping cart selection and reverse selection function example sharing

This article mainly introduces AngularJS to implement the function of selecting all and inverting the selection in the shopping cart. Friends who need it can refer to it. I hope it can help everyone.

Without further ado, I will post the code directly for you. The specific code is as follows;

nbsp;html>


 <meta>
 <title></title>
 <link>
 <style>
 .p1{
  margin: 20px;
 }
 </style>


<p>
 </p><h4 id="angularJS-购物车实现全选-取消全选">angularJS--购物车实现全选/取消全选</h4>
 <button>添加商品</button>
 <button>删除商品</button>
 <br><br>
 
                                       
操作check状态商品名称单价数量小计
{{p.checked}}||{{p.checked}}{{p.name}}单价:¥{{p.price}}数量: 小计:¥{{p.sum}}
 
 全选取消全选  

 已选择{{jishuqi}}件商品,总金额:¥{{ sumTotal }} <script></script> <script> angular.module(&#39;testMo&#39;,[&#39;ng&#39;]).controller(&#39;testCtrl&#39;,function($scope){ // $scope.p1=new Object(); // $scope.p1.price=10; // $scope.p1.count=1; //购物车应该是一个数组 $scope.selectAll=false;//全选默认为false $scope.cart=[{id:0,name:&#39;商品0&#39;,price:10,count:5,sum:10,checked:false}]; $scope.addProduct= function (){ var p=new Object(); p.id=$scope.cart.length; p.name=&#39;商品&#39;+ 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(&#39;cart&#39;,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>

PS: Let me share with you the code of the angularjs shopping cart. The specific code is as follows Shown:

nbsp;html>


  <meta>
  <title>购物车</title>
  <script></script>


<center>
<h2 id="商品列表">商品列表</h2>
<p>
  <!--导航栏-->
  <nav>
    <p>
      </p>
<p>
        </p>
<p>
          <input>   
           产品价格:
          <select>
            <option>0-1000</option>
            <option>1000-2000</option>
            <option>2000-5000</option>
          </select>   
          <input>
        </p>
      </nav></p>
    
  <br>
  <table>
    <thead>
    <tr>
      <th>
        产品编号
        <span></span>
      </th>
      <th>
        产品名称
        <span></span>
      </th>
      <th>
        产品价格
        <span></span>
      </th>
      <th>
        操作
        <span></span>
      </th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <td>
        {{item.id}}
      </td>
      <td>
        {{item.name}}
      </td>
      <td>
        {{item.price | currency:'(RMB)'}}
      </td>
      <td>
         <input>
      </td>
    </tr>
    </tbody>
  </table>

<script>
  angular.module(&#39;product&#39;,[])
    .factory(&#39;productList&#39;,function(){
      return [
        { id:910,name:"imac",price:15400 },
        { id:80,name:"iphone",price:5400 },
        { id:29,name:"ipad",price:14200 },
        { id:500,name:"ipad air",price:23400 },
        { id:1200,name:"ipad mini",price:22000},
        { id:100,name:"android",price:9990 }
      ]
    })
    .controller(&#39;productController&#39;,function($scope,productList){
      /*$scope.search = "ipad";//定义一个变量
      alert($scope.search);*/
      $scope.productList=productList
      $scope.orderColumn=&#39;name&#39;; //排序字段
      $scope.orderSign=&#39;-&#39;;   //为空时正序 为负号时倒序
      $scope.sortProduct=function(sortColumn){ //点击列标题排序事件
        $scope.orderColumn=sortColumn;//觉得按照那一列进行排序
        if($scope.orderSign=="-"){
          $scope.orderSign="";
        }else{
          $scope.orderSign=&#39;-&#39;;
        }
      };
      //删除产品
      $scope.delProduct = function(name){
        //alert(name);
        if(name!=""){
          if(confirm("是否删除"+name+"商品") ){
            var p;
            for (index in $scope.productList) {
              p = $scope.productList[index];
              if(p.name == name){
                $scope.productList.splice(index,1);
              }
            }
          }
        }
      }
      //清空购物车
$scope.removeAll = function(){
if(confirm("你确定要清空购物车所有商品吗?")){
$scope.productList = [];
}
}
    });
</script>
</center>

Okay, the code ends here.

Related recommendations:

JS checkbox all-selected and inverted method

JavaScript checkbox all-selected and inverted event Detailed implementation explanation

JQuery implementation of selecting all check boxes in the list and inverting the selection function encapsulation

The above is the detailed content of AngularJS implementation of shopping cart selection and reverse selection function example sharing. For more information, please follow other related articles on the PHP Chinese website!

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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software