How to Filter by Object Property in Angularjs

How to filter by object property in angularJS

You simply have to use the filter filter (see the documentation) :

<div id="totalPos">{{(tweets | filter:{polarity:'Positive'}).length}}</div>
<div id="totalNeut">{{(tweets | filter:{polarity:'Neutral'}).length}}</div>
<div id="totalNeg">{{(tweets | filter:{polarity:'Negative'}).length}}</div>

Fiddle

How to filter by object's property in AngularJS?

By default filters do contains search, you should make that filter to do strict comparison, by passing 3rd parameter to true to filter.

 ng-options="item.id as item.state_name for item in states
| filter : {country_id: { id : sellerCountry} }: true"

Demo Plunker

How do I apply a filter to a specific property in AngularJS?

You could do filter on single property, by having providing JSON object to filter.

Markup

Name
<input ng-model="search" type="text"/>

<ul>
<li ng-repeat="item in names | filter: {name: search }">{{item.name}}<li>
</ul>

Angularjs Filter On Object Property If Object Not Null

This is custom filter with arbitrary length of property chain(entity.name.data). If some property value is falsy(!val), item goes to output, otherwise it happens only if target value contains search goal(val.indexOf(value) != -1):

angular.module('app', []).controller('ctrl', function($scope){    this.users = [      {entity:{name:{data:'Max'}}, name: 'Max'},            {entity:{name:{data:'Sam'}}, name: 'Sam'},      {name: 'Henry'},      {entity: null, name: 'John'},                        {entity: {name:null}, name: 'Kate'},                        {entity: {name:{data:null}}, name: 'Tom'},                 ]}).filter('myfilter', function(){  return function(array, search){    var property = Object.keys(search)[0];    var value = search[property];    if(value){            var props = property.split('.');      return array.filter(x => {                for(var prop of props){          var index = props.indexOf(prop);          var last = props.length - 1;                    val = index == 0 ? x[prop] : val[prop];                              if(!val)            return true;          if(val && index == last)            return val.indexOf(value) != -1;                            }              });    }    return array;  }})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl as ctr'> <input type='text' ng-model='filterEntityName'/> <div class="row" ng-repeat="user in ctr.users | myfilter:{entity.name.data:filterEntityName}"> {{user | json}} </div></div>

AngularJS - Filter by any of the properties

If I understand correctly, an object being searched (we'll call it target) is a match if:

  • both searchObj and target share at least one property name at the same level

  • The value of target's property is equal to or contains the value of searchObj's property

The code below (which includes your edits) should do what you need. I'll leave it to you to fill in any edge cases (checks for hasOwnProperty, comparison of different types, etc.). I think filtering like this should only happen when necessary, like when a user types. Creating an Angular filter out of this could be too expensive, since it runs on each digest cycle:

function objectContains(searchObj, target) {
for (var property in searchObj) {
var searchVal = searchObj[property];
var targetVal = target[property];

if (isObject(searchVal) && isObject(targetVal)) {
if(objectContains(searchVal, targetVal)){
return true;
}
}

if (
!isObject(searchVal) && !isObject(targetVal) &&
!isUndefinedOrNull(targetVal) &&
!isUndefinedOrNull(searchVal) &&
targetVal.toString().indexOf(searchVal.toString()) !== -1
) {
return true;
}
}

return false;
}

function isUndefinedOrNull(x) {
return typeof x === "undefined" || x === null;
}

function isObject(x) {
return typeof x === "object";
}

var filtered = list.filter(function(item) {
return objectContains(searchObj, item);
});

AngularJS Filter Object Property

By changing items to array:

 $scope.items =[ 
{
id:'123',
color: 'red',
quantity: 3
},
{
id:'456',
color: 'blue',
quantity: 7
}
];

You can use built in filter which is only available for arrays ( there was talk of object filtering also, not sure if it exists yet)

 <li ng-repeat="item in items | filter: {id:selected}">
{{item.color}}
</li>

In general it is better to work with array data that allows sorting, filtering, indexing etc much easier than with objects

DEMO

AngularJS- How to filter by property/ attribute of an object- forEach is not a function

A for...in loop iterates over the enumerable property names of an object. You then need to access the object using that property name to get the value. Here's an example:

console.log('Using for...in on an object:');
var myObj = { 'prop1': 'Hello world!', 'prop2': 12345, 'some crazy property': null};
for (var propName in myObj) {
console.log('propName is ' + propName);
//Now we can lookup the value using that property name. var propValue = myObj[propName];
console.log('myObj[' + propName + '] is ' + propValue);
}

How to filter by an specific attribute in an object in AngularJS?

Here is a simple working Fiddle of what your try to achieve. It does filter your object by attribute genre where you can search for the Id in the text field. For example 8.

Take a look at the filter declaration filter:{genre:searchGenre} which holds the attribute name genre to filter and the model input searchGenre. For more information please take a look at the AngularJS Documentation of filter.


The following example shows how to filter in View - Fiddle demo

View

<div ng-controller="MyCtrl">
<h1>Filter items</h1>
<input type="text" ng-model="searchGenre">
<h2>Genres</h2>
<div ng-repeat="genre in genres | filter:{genre:searchGenre}">
{{genre.label}}
</div>
</div>

AngularJS app

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.genres = [{
label: "Trance",
genre: "8",
position: 8
}, {
label: "House",
genre: "2",
position: 8
}];
}

The following example shows how to filter in an controller - Fiddle demo

View

<div ng-controller="MyCtrl">
<div>Filter items</div>
<input type="text" ng-model="searchGenre">
<div>Genres</div>
<div ng-repeat="genre in filtered">
{{genre.label}}
</div>
</div>

AngularJS App

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, filterFilter) {

$scope.genres = [{
label: "Trance",
genre: "8",
position: 8
}, {
label: "House",
genre: "2",
position: 8
}];

//init search phrase
$scope.searchGenre = '';

//init filtered scope
$scope.filtered = [];

/**
* Watch keyword change
*/
$scope.$watch('searchGenre', function(term) {
$scope.filtered = filterFilter($scope.genres, {'genre': term});
});
}


Related Topics



Leave a reply



Submit