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

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

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

页面代码html

<!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代码java

<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()函数angularjs

相关文章
相关标签/搜索