13

你如何用 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

4 回答 4

25

创建自定义过滤器。

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;
    }
});
于 2013-08-05T11:07:32.567 回答
15

你可以使用"ng-show="friend.age >=26"和ng-repeat="friend in friends",它只会显示年龄大于等于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>
于 2015-12-22T10:13:18.003 回答
7

这是工作小提琴

   $scope.call = function(a){

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

}
于 2013-08-05T11:20:30.923 回答
4

我使用了一个过滤器ng-repeat

<div ng-repeat="product in products | filter:{ colour: by_colour }">
于 2017-12-07T10:02:44.827 回答