Search code examples
angularjsangularjs-ng-repeatangularjs-animation

Live search in AngularJS: updating the results


I want a live search: the results are queried from web api and updated as the user types.

The problem is that the list flickers and the "No results" text appears for a fraction of second, even if the list of results stays the same. I guess I need to remove and add items with special code to avoid this, calculating differences between arrays, etc.

Is there a simpler way to avoid this flicker at least, and probably to have possibility to animate the changes?

It looks like this now:

How live search looks like

The html part is:

    <div class="list-group">
        <a ng-repeat="test in tests track by test.id | orderBy: '-id'" ng-href="#/test/{{test.id}}" class="list-group-item">
            <h4 class="list-group-item-heading">{{test.name}}</h4>
            {{test.description}}
        </a>
    </div>
    <div ng-show="!tests.length" class="panel panel-danger">
        <div class="panel-body">
            No tests found.
        </div>
        <div class="panel-footer">Try a different search or clear the text to view new tests.</div>
    </div>

And the controller:

testerControllers.controller('TestSearchListCtrl', ['$scope', 'TestSearch',
function($scope, TestSearch) {
    $scope.tests = TestSearch.query();
    $scope.$watch('search', function() {
        $scope.tests = TestSearch.query({'q':$scope.search});
    });
}]);

Solution

  • You should use ng-animate module to get the classes you need for smooth animation. For each ng-repeat item that's moved, added, or removed - angular will add specific classes. Then you can style those classes via CSS or JS so they don’t flicker.