0

I have a basic angular app that sorts and filters a list of species from a local json file. When the app initializes none of the species are returned. When you begin to type some species are returned, and if you delete your search terms all species are returned.

I would like all species to be returned when the app initializes.

http://plnkr.co/edit/0DOwSvtaepSfFWKR8UGS?p=info

2 Answers 2

1

I think it's neater to use the inline notation for filter, which avoids this problem:

<div ng-repeat="animal in species | filter:query | orderBy:orderProp")>

NOTE: you can then remove the code that sets up the $watch on query

EDIT: as you specifically want it in the controller:

The reason your filter is initialising to blank, is because your $scope.species data is being populated asynchronously. When the first $watch is triggered, there is no data to filter. This stays the case until you input a query.

To solve this, set up the $watch after the data has arrived, like so:

$http.get('species.json').success(function(data) {
    $scope.species = data;
    $scope.$watch('query', function (query) {
        $scope.filteredData = $filter('filter')($scope.species, query);
    });
});

Alternatively you could manually run the filter function once, inside the success callback.

Sign up to request clarification or add additional context in comments.

1 Comment

The reason I moved this to the controller is so that it can be reused in different views. I just have the one view right now, but I'm going to add a "table" view as well.
1

Have you tried setting filteredData to the data returned from the get?

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.