1

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.

1
  • 1
    much better to make items an array, then can use filter and property in html based on predicate selected Commented Jul 15, 2015 at 16:58

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.