Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular filter in ng-repeat with deep object

I am following this question to filter ng-repeat by a field

ng-repeat :filter by single field

However my case is different, it's actually a field in the object value of the main object. Basically I want to show only data.a == 1

The following code works on the first list. The second list gives me error:

angular.module('myapp', [])
.controller('mainCtrl', function ($scope) {
    $scope.items = [{
        name: "John",
        data: {
            a: 1
        }
    }, {
        name: "Lee",
        data: {
            a: 2
        }
    }, {
        name: "Rue",
        data: {
            a: 3
        }
    }, {
        name: "Peter",
        data: {
            a: 1
        }
    }];
});

HTML

<div ng-controller="mainCtrl">
    <h1>List 1</h1>
    <p ng-repeat="item in items">{{ item.name }}</p>
    <h1>List 2</h1>
    <p ng-repeat="item in items | filter: {data.a :1}">{{ item.name }}</p>
</div>

http://plnkr.co/edit/nh4GryqZJbEiXSzMzTKk

Any help on how to do this or is there a nicer way?

UPDATE 1

I tried angular.filter filterBy and it didn't work either. Giving me blank array.

http://plnkr.co/edit/nh4GryqZJbEiXSzMzTKk?p=preview

    <p ng-repeat="item in items | filterBy: ['item.data.a'] :1">{{ item.name }}</p>

UPDATE 2

I tried this below

<p ng-repeat="item in items | filter: {data :{a:1}}">{{ item.name }}</p>

It seems to work but I need exact match, not substring match. I read this but not seem to find a way to add true AngularJS Filter Exact Match

Any clue?

UPDATE 3 (CORRECT ANSWER):

This works http://plnkr.co/edit/qJl6MtY6fOlVtD9Rv999?p=preview

Basically I added this to the controller

$scope.filteredItems = $filter('filter')($scope.items, {data :{a:1}}, true); 

and do ng-repeat on filteredItems instead. I don't see a way to pass true param in the view directly.

like image 788
HP. Avatar asked Mar 19 '15 09:03

HP.


2 Answers

If you want to access the inner property you need to access it with object notation:

<p ng-repeat="item in items | filter: {data :{a:1}}">{{ item.name }}</p>

Check this plunker.

like image 142
eladcon Avatar answered Nov 12 '22 14:11

eladcon


If you are using \ can upgrade to angular 1.3, then you can use this: 1.3 filters These are faster. In particular, you can use filterBy

See: plunkr example

<p ng-repeat="item in items | filterBy: ['data.a'] :1">{{ item.name }}</p>

Otherwise, use a custom function. See my answer here: custom function

like image 3
trees_are_great Avatar answered Nov 12 '22 15:11

trees_are_great