AngularJS 1.0 案例 购物车计算器
<!DOCTYPE html> <html lang="en" ng-app="M20"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body> <section class="container" ng-controller="C20"> <p>完整版购物车计算器</p> <button class='btn btn-success' ng-click='addProduct()'>添加商品</button> <hr/> <div> <p ng-repeat="(index, item) in cart" class='alert alert-success'> 单价:<span ng-bind='item.price'></span> 数量:<input type='number' ng-model="item.count"> 小计:<span ng-bind='item.price*item.count'>0</span> </p> </div> <div>总计:<span ng-bind='getTotal()'></span></div> </section> <script src="js/jquery-1.11.3.js"></script> <script src="js/angular.js"></script> <script> angular.module('M20', ['ng']). controller('C20', function($scope, $interval){ $scope.cart = [] $scope.cart.push({price: 10.5, count: 2}); $scope.cart.push({price: 5.5, count: 5}); $scope.addProduct = function(){ let p = {price: Math.round(Math.random()*500)/10, count: Math.ceil(Math.random()*10)} $scope.cart.push(p); console.log($scope.cart.count); } $scope.getTotal = function(){ let total = 0; angular.forEach($scope.cart, function(v, k){ total += v.count * v.price; console.log(v); }) return total } }) </script> </body> </html>