0

I have json data with following information

[
{
"city":"Bangalore",
"dob":"04-Oct-2014",
"age":24,
"maritalStatus":"Single"
},
{
"city":"Bangalore",
"dob":"04-Oct-2014",
"age":24,
"maritalStatus":"Single"
},
{
"city":"Chennai",
"dob":"04-Oct-2014",
"age":24,
"maritalStatus":"Single"
}
]

This data shown in list format

<ul class="userInfo">
<div   ng-repeat="user in users " >
  <li class="btn-default">
    <div class="userDetails">
      <div class="userPosition">{{user.city}}</div>
    </div>
  </li>
  </div>
</ul>

During HTTP request

userDirectory.controller("userListControl", function($scope,$rootScope, $http)
        {

            $http.get('data/userData.json').success (function(data){
               $scope.users = data;
        var usersDb = TAFFY();
        usersDb.insert(data);
            });
    });

Here, The data is coming from userData.json file.

My Question is,

Before the loading page. I will declare city = "bangalore".

So based on city. I have to show the data based on city. I want to avoid other datas except city:bangalore from json.

How can i filter particular city datas. I dont want use filter function. I have to filter at this stage

$scope.users = data; Because i am using JS Db here. Then only i can store these data here and process in future

Mohaideen Ismail
  • 314
  • 4
  • 21
  • Possible Duplicate: [How to use a filter in a controller?](http://stackoverflow.com/questions/14302267/how-to-use-a-filter-in-a-controller) – Umayr Nov 07 '14 at 05:56

2 Answers2

2

I am not sure about your exact scenario but you can very well do

 $http.get('data/userData.json').success (function(data){
    var city='bangalore';   //can be set anywhere 
    $scope.users = data.filter(function(item){return item.city===city;});
    var usersDb = TAFFY();
    usersDb.insert($scope.users);
 });

Array.filter works on all modern browsers (ie 9 and above)

Else implement an Angular filter and use it the controller using $filter service:

Chandermani
  • 42,589
  • 12
  • 85
  • 88
0

Yes, you can injecto $filter into your controller like this:

userDirectory.controller("userListControl", function($scope,$rootScope, $http, $filter)
    {

        $http.get('data/userData.json').success (function(data){
           var cityFilter = {city: 'Bangalore'};

           $scope.users = $filter('filter')(data, cityFilter); //Then here is your result.
           var usersDb = TAFFY();
           usersDb.insert(data);
        });
});

Here is $filter document in angularjs.

Tyler.z.yang
  • 2,402
  • 1
  • 18
  • 31