1. 程式人生 > >angular 雙向綁定demo

angular 雙向綁定demo

sco rep PE color check count toggle module col

技術分享圖片

  1 <!DOCTYPE html>
  2 <html lang="en" ng-app="myApp">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>angular 點餐</title>
  6     <script src="js/angular.js"></script>
  7 </head>
  8 <body ng-controller="myCtrl">
  9 <div style
="width:400px"> 10 <h1 ng-bind="appName"></h1> 11 <h4 ng-bind="restaurant"></h4> 12 <hr> 13 <table> 14 <th ng-repeat="head in th" ng-bind="head" ></th> 15 <tr ng-repeat="food in meal" > 16 <td><
input type="checkbox" ng-model="food.isCheck" ng-click="select()" ng-checked="food.isCheck"></td> 17 <td ng-bind="food.name"></td> 18 <td ng-bind="food.price|moneyFormat"></td> 19 <td ng-bind="food.quantity"></td> 20 21
<td ng-click="count(food,-1);select()">-</td> 22 <td ng-init="key=$index" ng-click="del($index);select()">刪除</td> 23 <td ng-click="count(food,1);select()">+</td> 24 25 <td ng-bind="food.price*food.quantity|moneyFormat"></td> 26 27 </tr> 28 </table> 29 <hr> 30 <h4><input type="checkbox" ng-model="checkAll" ng-click="toggleSelect();select()" ng-checked="checkAll">全選</h4> 31 <h4>合計: <span ng-bind="totalprice|moneyFormat" ></span></h4> 32 33 34 </div> 35 36 <script> 37 var app =angular.module(myApp,[ng]); 38 app.controller(myCtrl,function($scope){ 39 $scope.appName=我餓了; 40 $scope.restaurant=xl美食; 41 $scope.th=[選擇,商品,價格,數量,-,刪除,+,小計]; 42 // $scope.isCheck=false; 43 $scope.meal=[{name:紅燒肉蓋飯,price:19,quantity:1,isCheck:false}, 44 {name:梅菜扣肉蓋飯,price:19,quantity:1,isCheck:false}, 45 {name:肥牛飯,price:18,quantity:1,isCheck:false}, 46 {name:咖喱雞,price:17,quantity:1,isCheck:false}, 47 {name:鹵蛋,price:2,quantity:1,isCheck:false}, 48 {name:鹵肉飯,price:18,quantity:1,isCheck:false} 49 ]; 50 $scope.select=function(){ 51 $scope.checkAll=true; 52 53 //遍歷選擇的商品 54 angular.forEach($scope.meal,function(val,key){ 55 // console.log(‘已選擇‘+val.name); 56 $scope.checkAll=$scope.checkAll&&val.isCheck; 57 }) 58 //合計價格 59 $scope.totalprice=0; 60 angular.forEach($scope.meal,function(val,key){ 61 // console.log(‘已選擇‘+val.name); 62 if(val.isCheck){ 63 $scope.totalprice+=val.price*val.quantity; 64 } 65 }) 66 } 67 68 $scope.toggleSelect=function(){//點擊全選/取消全選的時候,遍歷商品列表更換選中的值 69 angular.forEach($scope.meal,function(val,key){ 70 val.isCheck=$scope.checkAll; 71 }) 72 } 73 74 $scope.del=function(index){ 75 console.log(index); 76 $scope.meal.splice(index,1); 77 } 78 79 $scope.count=function(object,num){ 80 object.quantity+=num; 81 if(object.quantity<1){ 82 object.quantity=1; 83 } 84 85 } 86 87 88 }); 89 //金額的過濾器 90 app.filter(moneyFormat,function(){ 91 return function(val){ 92 if(val){//判斷是否有值 93 return +val.toFixed(2)+ 94 95 }else{ 96 val=0; 97 return +val.toFixed(2)+ 98 99 } 100 101 } 102 103 }) 104 105 </script> 106 </body> 107 </html>

如有復制,請註意js文件路徑.

angular 雙向綁定demo