angularJs(ng-repeat)过滤出指定数据

ng-repeat 指令会重复一个 HTML 元素

有时接收到的数据不需要全部显示到页面上,这时就可以使用过滤器。过滤器可以使用一个管道字符(|)添加到表达式和指令中。 可参考AngularJS 过滤器
本示例通过自定义过滤器,过滤出指定对象数组中指定key为指定value的对象。

页面代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
    <style>
     ul > li {
        list-style: none
     }
     .active {
        background-color: red!important;
        border: 1px solid #000000;
     }
    </style>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <ul>
        <!-- 动态设置宽高 ,显示满足指定属性值的数据-->
        <li ng-repeat="(i,item) in names | filterRow :'width':300" 
        ng-class="{'active': item.width === 100}"         
        style="background-color: skyblue;width:{{ item.width }}px; height: {{ (i+1) * 100 }}px;">
          {{ item.name + ", " + item.country }} --> {{(i*i+10)*20}}
        </li>
      </ul>
    </div>    
  </body>
</html>

JS代码

<script>
      var app = angular.module("myApp", [])
      app.controller("myCtrl", function($scope) {
        $scope.names = [
          {width:100, name: "Jani", country: "Norway" },
          {width:200, name: "Hege", country: "Sweden" },
          {width:300, name: "Kai", country: "Denmark" }
        ];
      });
     //  设置过滤器,过滤指collection中keyName值为value的数据
      app.filter('filterRow',function(){         
        return function(collection,keyName,value){
            var output = []
            angular.forEach(collection, function (item) {
                console.log("item[keyName]->"+item[keyName])
                if(item[keyName] === value){
                    output.push(item)
                }
            })
            console.log(output.length)
            return output
        };
      })
    </script>

可以根据实际情况自定义filter中function()函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值