在Ng-Repeat中搜索而不隐藏任何内容

时间:2017-06-01 06:15:49

标签: angularjs angularjs-ng-repeat ng-filter

标题可能有点令人困惑。请看下面的代码,

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<input type="text" ng-model="test"><br/>
<div ng-repeat="x in names | filter:test"> {{ x }}</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
});
</script>
</body>
</html>

使用这些代码,我可以从scope.names中搜索名称。但问题是,我不想在搜索特定名称时隐藏其他结果。这意味着,当我搜索&#34; Gustav&#34;时,它应该在列表的顶部而不隐藏其他名称。如果名称按提供的关键字匹配排序会更好。请帮助。

1 个答案:

答案 0 :(得分:1)

OrderBy是达到预期效果的选项之一:

<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<input type="text" ng-model="test"><br/>
<div ng-repeat="x in names | orderBy:customOrdering"> {{ x }}</div>
{{ log }}

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.test = "";
$scope.names = [
    'Jani',
    'Carl',
    'Margareth',
    'Hege',
    'Joe',
    'Gustav',
    'Birgit',
    'Mary',
    'Kai'
];
$scope.customOrdering = function(a) {
    return a.indexOf($scope.test) == -1;
    //return a.toUpperCase().indexOf($scope.test.toUpperCase()) == -1;   
    // use that for case insensitive search
}
});
</script>
</body>
</html>