haakon.io
haakon.io

Reputation: 477

UI-Grid Single Filter not working with complex data?

I'm using UI-Grid and I have some complex data that I'm trying to apply a filter to using their single filter example. If I use simple selectors, everything works great. The second I try to go one level down into other data within the same node it stops working.

My plnkr is here

Here is my filter func. If I were to change 'address.state' to 'email' it would start working:

  $scope.singleFilter = function( renderableRows ){
    var matcher = new RegExp($scope.filterValue);
    renderableRows.forEach( function( row ) {
      var match = false;
      [ 'name', 'company', 'address.state' ].forEach(function( field ){
        if ( row.entity[field].match(matcher) ){
          match = true;
        }
      });
      if ( !match ){
        row.visible = false;
      }
    });
    return renderableRows;
  };

Here is a node from the data.json so you can get a feel for the data structure:

{
    "id": 0,
    "guid": "de3db502-0a33-4e47-a0bb-35b6235503ca",
    "isActive": false,
    "balance": "$3,489.00",
    "picture": "http://placehold.it/32x32",
    "age": 30,
    "name": "Sandoval Mclean",
    "gender": "male",
    "company": "Zolavo",
    "email": "[email protected]",
    "phone": "+1 (902) 569-2412",
    "address": {
        "street": 317,
        "city": "Blairstown",
        "state": "Maine",
        "zip": 390
    },
    "about": "Fugiat velit laboris sit est. Amet eu consectetur reprehenderit proident irure non. Adipisicing mollit veniam enim veniam officia anim proident excepteur deserunt consectetur aliquip et irure. Elit aliquip laborum qui elit consectetur sit proident adipisicing.\r\n",
    "registered": "1991-02-21T23:02:31+06:00",
    "friends": [
        {
            "id": 0,
            "name": "Rosanne Barrett"
        },
        {
            "id": 1,
            "name": "Nita Chase"
        },
        {
            "id": 2,
            "name": "Briggs Stark"
        }
    ]
},

Upvotes: 0

Views: 230

Answers (1)

litel
litel

Reputation: 3980

You cannot select multiple levels of an array using bracket notation, hence your error; the bracket notation is equivalent to dot notation. You could design a function to comb through several levels of intervals (like this SO answer), or just add another if conditional to check if field has a dot inside, and use split to turn it into an array. If you only have a few items in your array, the latter is probably easier.

   [ 'name', 'company', 'address.state' ].forEach(function( field ){
    if (field.indexOf('.') !== '-1' ) {
        field = field.split('.');
    }
        if ( row.entity.hasOwnProperty(field) && row.entity[field].match(matcher) || field.length === 2 && row.entity[field[0]][field[1]].match(matcher)){
          match = true;
        }
      });

Upvotes: 1

Related Questions