I'm new to angularJS. I have a requirement to perform a search on JSON data. Here is an example JSON structure
countries = [
{
"country_name" : "India",
"stations" : [
{
"name": "Dream Factory"
}
]
},
{
"country_name" : "Indonesia",
"stations" : [
{
"name": "Drummer Factory"
},
{
"name": "Beats"
}
]
}
]
Say I type Ind
, I need the countries matching the string and return both India
and Indonesia
also In other field, typing Factory
should retrieve station names which matches the string (here Drummer Factory
, Dream Factory
).
What is the simple way to achieve this? Is there any built-in directive which solves this or can I use filters, If yes, please post with example...
You can use the filter named 'filter' (yes it's a little confusing): http://docs.angularjs.org/api/ng.filter:filter
Here's a demo: http://jsfiddle.net/g/pXnRs/4/
HTML:
<div ng-controller="CountryController">
Filter: <input ng-model="nameFilter" />
<ul>
<li ng-repeat="country in countries | filter: nameFilter">
{{country | json}}
</li>
</ul>
</div>
JS:
var app = angular.module('app', []);
app.controller('CountryController', function($scope){
$scope.nameFilter = '';
$scope.countries = [
{
"country_name" : "India",
"stations" : [
{
"name": "Dream Factory"
}
]
},
{
"country_name" : "Indonesia",
"stations" : [
{
"name": "Drummer Factory"
},
{
"name": "Beats"
}
]
}];
});
angular.bootstrap(document, ['app']);
If you need stations only as results, you should first flatten the JSON object hierarchy into a list of stations.