Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter JSON-Data with AngularJs?

I have an array (_users) that contains JSON objects.

{ 
  "User":
  {
    "userid":"19571",
    "status":"7",
    "active":"1",
    "lastlogin":"1339759025307",
    "Stats":
     [
       {
         "active":"1",
         "catid":"10918",
         "typeid":"71",
         "Credits":
         [
           {
             "content":"917,65",
             "active":"1",
             "type":"C7"
           },               
           {
             "content":"125,65",
             "active":"1",
             "type":"B2"
           }
         ]
       }
     ]
  }
}

1- How can I filter only users with "active":"1" not "0"

I have tried something like this:

<div ng-repeat="user in _users | filter:active | orderBy:user.userid">
    {{user.userid}}
</div>

but not working correctly for me.

Thank you!

like image 591
Vural Avatar asked Aug 12 '12 14:08

Vural


People also ask

Which AngularJS filter formats an object to a JSON string?

The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.

What is JSON filter?

The json filter converts a JavaScript object into a JSON string. This filter can be useful when debugging your applications. The JavaScript object can be any kind of JavaScript object.

How do I access JSON data?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

What is JSON Stringify in angular?

The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

Since your object model is kind of complex I would recommend using custom filtering function:

$scope.isActive = function(user) {
    return user.User.Stats[0].active === "1";
};

and then in your HTML:

<div ng-repeat="user in _users | filter:isActive">
    {{user.User.userid}}
</div>

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/4kzzy/3/

Be sure to check angular's documentation on filters if you need more info: http://docs.angularjs.org/api/ng.filter:filter

like image 200
pkozlowski.opensource Avatar answered Oct 14 '22 11:10

pkozlowski.opensource


Taking @pkozlowski.opensource a bit further and allowing live filtering of items/users:

http://jsfiddle.net/hbyNN/

<div ng-controller="MyCtrl">
  <label>userid substring filter:</label>
  <input ng-model="zzzzz">

  <div ng-repeat="user in _users | filter:isInteresting"> 
      <pre>{{user | json}}</pre>
  </div>
</div>

And:

   $scope.isInteresting = function (user) {
    if ($scope.zzzzz == undefined) {
        return true;
    }

    return user.userid.indexOf($scope.zzzzz) !== -1;
};
like image 25
okigan Avatar answered Oct 14 '22 09:10

okigan