Angular js的ng-repeat

                                                               重复语句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指令返回的是布尔值 .

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值