简体   繁体   中英

AngularJS Filter Object Property

My code is outputting:

  • red
  • green

Using the model of $scope.selected = '123' how can I edit it to only output:

  • red

Here's my view:

  <body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="item in items">
        {{item.color}}
      </li>
    </ul>
  </body>

Here's my controller:

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

app.controller('MainCtrl', function($scope) {
  $scope.selected = '123';
  $scope.items = {
    '123': {
      color: 'red',
      quantity: 3
    },
    '456': {
      color: 'blue',
      quantity: 7
    }
  };
});

I tried using a filter with selected but didn't have any luck.

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

You can create a filter for this

.filter('myFilter', function() {
            return function(obj, selected) {
                if (!selected) return obj;

                return {
                    value: obj[selected]
                }
            }
        }

here is an example

Filters will only work on arrays, and as charlietfl mentioned you should probably switch it to that. If you can't you can use this, though I highly recommend against it:

  <body ng-controller="MainCtrl">
     <ul>
      <li ng-repeat="(key, item) in items" data-ng-if="key == selected">
           {{item.color}}     
      </li>
  </ul>
  </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM