angular初始用——简易购物车

 1 <html>
 2   <head>
 3     <meta charset="utf-8">
 4     <script src="js/angular.js"></script>
 5     <script src="js/mult_app.js"></script>
 6     <link rel="stylesheet" href="css/bootstrap.css">
 7     <style>
 8       .nested {
 9         border: 1px solid red;
10         margin-left: 2em;
11         padding: 1em;
12       }
13     </style>
14   </head>
15   <body ng-app="MyApp">
16     //angularjs版本的多个购物车
17     <div ng-controller="MyCar">
18       <ul ng-repeat="item in carList">
19         <li>名字{{item.name}} 数量&nbsp;&nbsp;<span ng-click="minus(item.index)">-</span>&nbsp;&nbsp;{{item.num}}&nbsp;&nbsp;<span ng-click="plus(item.index)">+</span> 价格{{item.price}}
20         <span ng-click="remove(item.index)">删除</span>
21         </li>
22       </ul>
23       总价 {{totalPrice}}
24     </div>
25   </body>
26 </html>
 1 var app = angular.module("MyApp", []);
 2 
 3 var carList = [{
 4     name: "牛奶",
 5     price: 20,
 6     num: 1
 7 },{
 8     name: "鮮花",
 9     price: 5,
10     num: 1
11 },{
12     name: "水果",
13     price: 10,
14     num: 1
15 },{
16     name: "鸡蛋",
17     price: 2,
18     num: 1
19 }];
20 function wrapData(data){
21      for(var i =0; i< data.length; i++) {
22         data[i].index = i;
23         data[i].initPrice = data[i].price;
24      }
25 }
26 function store(namespace, data) {
27     if(arguments.length > 1) {
28         localStorage.setItem(namespace, JSON.stringify(data));
29     }else {
30         var obj = localStorage.getItem(namespace);
31         return (obj && JSON.parse(obj)) || null
32     }
33 }
34 function getTotalPrice(data){
35     var totalPrice = 0;
36     for(var i =0; i< data.length; i++) {
37       totalPrice+= data[i].num * data[i].initPrice
38     }
39     return totalPrice;
40 }
41 wrapData(carList);
42 
43 
44 app.controller("MyCar", function($scope) {
45   //模块作用域
46   $scope.carList = store('mycar') || carList;
47   $scope.totalPrice = getTotalPrice(carList);
48   $scope.$watch("carList", function(newvalue, oldvalue){
49       $scope.totalPrice = getTotalPrice($scope.carList);      
50       store('mycar', $scope.carList);
51   }, true);
52   $scope.remove = function(index){
53          $scope.carList.splice(index, 1);
54   }
55   $scope.plus = function(index){
56       $scope.carList[index].num ++;
57       $scope.carList[index].price += $scope.carList[index].initPrice;
58   }
59   $scope.minus = function(index){
60       $scope.carList[index].num --;
61       $scope.carList[index].price -= $scope.carList[index].initPrice;
62   }
63 });
64 
65 app.controller("AnotherCtrl", function($scope) {
66   $scope.firstUser = 'Peter';
67 });
原文地址:https://www.cnblogs.com/thestudy/p/5648015.html