angularjsangularjs-ng-repeatng-filter

Search in Ng-Repeat without hiding anything


The title may be a bit confusing. Please take a look at the code below,

<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>

with these codes i can search for a name from scope.names. But the problem is, i don't want to hide other results while searching for a particular name. Which means, when i search "Gustav", it should be on top of the list without hiding other names. It would be more great if names were sorted by the matching of supplied keyword. Please help in this.


Solution

  • OrderBy is one of the options for the desired effect:

    <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>