1

I'm trying to use $filter to filter dataset retrieved from a JSON file within a controller. here is the data in the JSON file:

[{
    "keyword": "key1",
    "path": "path1"
}, {
    "keyword": "key2",
    "path": "path2"
}, {
    "keyword": "key3",
    "path": "path3"
}, {
    "keyword": "key4",
    "path": "path4"
}, {
    "keyword": "key5",
    "path": "path5"
}]

Then I get the data within my controller like this:

$http.get('/sampleJson.txt').then(function (response) {
    vm.resultSet=response.data;
});

and then I use $filter to filter the data:

vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});

Finally I use ng-repeat to show the data in the view:

<tbody>
    <tr ng-repeat="result in vm.results">
    <td><a href="{{result.path}}">{{result.keyword}}</a></td>
   <td>{{result.keyword}}</td>
   </tr>
</tbody>

However the results variable is empty and nothing shows up. It seems to be pretty basic stuff, however I can not figure out what is wrong? PS: When I declare other variables in the controller like :

vm.message="Hello, Angular!"

It shows up in the view.

2 Answers 2

3

I wrote a solution using $scope. The filter in this solution works. I don't know why you use vm but the $http service works asincronously, and the line

vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});

should be in the body of the then() function.

Here is a plunk

https://plnkr.co/edit/gwx90oN0cf62JuUF5t2k?p=preview

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

Comments

2

$http is asynchronous, .then (vm.resultSet=response.data;) executed (when promise get resolved) after vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});

Try this,

$http.get('/sampleJson.txt').then(function (response) {
    vm.resultSet=response.data;
    vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});
});

1 Comment

Yeah you are right. I accepted the other answer as the solution just because was posted a bit earlier. Thanks

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.