重复语句ng-repeat
ng-repeat可以遍历一个数组中的数据并循环输出,这样显示一个表格就显得很简单.
1.首先定义要显示的数据的数组:
<script> var app=angular.module("myApp",[]); app.controller("myCtrl",function($scope){ $scope.productList=[ {"classification": "饮料","name": "可口可乐","price": "3", "unit": "瓶"}, {"classification": "饮料","name": "雪碧", "price" : "3", "unit": "瓶"}, {"classification": "水果", "name": "苹果", "price" : "5.5", "unit": "斤"}, {"classification": "水果", "name": "荔枝", "price": "15", "unit": "斤"}, {"classification": "生活用品","name": "电池", "price" : "2", "unit": "个",}, {"classification": "食品", "name": "方便面", "price": "4.5", "unit": "袋"} ] }) </script>
2.然后在html中编写如下代码:
<div class="mainTable" ng-controller="myCtrl"> <table class="tableList"> <th>分类</th> <th>名称</th> <th>单价(元)</th> <th>单位</th> <th></th> <tr ng-repeat="product in productList"> <td>{{product.classification}}</td> <td>{{product.name}}</td> <td>{{product.price}}</td> <td>{{product.unit}}</td> <td><button ng-click="addButtonEvent(product)">加入购物车</button> </td> </tr> </table> </div>
上面的点击函数中product参数为被点击当前行的数据内容,Angular js的ng-repeat可以直接把当前行的数据作为参数进行传递,在addButtonEvent()函数中就可以获取.
3.Angular js提供了$index字段可以获得当前元素在数组中的下标,
//如果把上边的点击事件函数的参数换成$index,就可以知道表格中哪个按钮被点击并且还可以知道该数据在数组中的位置下标 <td><button ng-click="addButtonEvent($index)" class="button">加入购物车</button></td>
4.ng-show还可以对ng-repeat要显示的数据进行过滤后再显示,例子如下:
<tr ng-repeat="product in productList" ng-show="$index>0"> <td>{{product.classification}}</td> <td>{{product.name}}</td> <td>{{product.price}}</td> <td>{{product.unit}}</td> <td><button ng-click="addButtonEvent(product)" class="button">加入购物车 </button></td> </tr> //对ng-show设置为$index>0,这样数组就会从第二个元素开始显示.也可以对$index就行其他的限制5.可以通过$first、$middle及$last知道当前元素是否是数组中的第一个元素、中间的某个元素,或者最后一个元素 ,此时ng-repeat指令返回的是布尔值 .