角度ng-重复条件

时间:2013-08-05 10:43:30

标签: javascript angularjs angularjs-directive

你如何使用ng-repeat进行角度测量? 我将使用文档中的示例,其中包含2个朋友的数组,如果我只想对所有26岁及以上的朋友重复一次,该怎么办?

    <!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
<body>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</body>
</html>

4 个答案:

答案 0 :(得分:24)

创建自定义过滤器。

HTML:

<html ng-app="someApp">

<li ng-repeat="friend in friends | age">

JS:

var someApp=angular.module('someApp', []);

someApp.filter('age', function() {
    return function(input, uppercase) {
        var out = [];
        for (var i = 0; i < input.length; i++) {
            if(input[i].age >= 26){
                out.push(input[i]);
            }
        }
        return out;
    }
});

答案 1 :(得分:14)

你可以使用ng-show =“friend.age&gt; = 26”与朋友中的ng-repeat =“朋友”。它只会显示年龄大于等于26岁的朋友。

<body>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
      I have {{friends.length}} friends. They are:
     <ul>
         <li ng-repeat="friend in friends" ng-show="friend.age >=26">
           [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
        </li>
    </ul>
</div>
</body>

答案 2 :(得分:6)

这是工作fiddle

   $scope.call = function(a){

    if (a.age > 26)
        return true;
    else
        return false;

}

答案 3 :(得分:3)

我在ng-repeat中使用过滤器:

<div ng-repeat="product in products | filter:{ colour: by_colour }">