0

In angular, given a $scope like this

$scope.colors=[{
 "key":1, 
 "color":"yellow"
},{
 "key":2, 
 "color":"pink"
},{
 "key":3, 
 "color":"black"
}];

If I want to access one of the properties in the view I can do it like this

{{colors[2].color}}

But if I don't know in advance what would be the order of the elements in the scope, would it be possible, for example, calling the property color of the object whose key is 1? Something like {{colors["key"=3].color}} but in an "Angular way". Thanks in advance!

Joe82
  • 1,357
  • 2
  • 24
  • 40
  • try with my answer in http://stackoverflow.com/questions/39470290/how-can-i-return-an-index-location-for-an-item-in-a-json-array-by-searching-with/39470512#39470512 it will return you the index of the wanted color.. in angular way use angular.forEach – AB Udhay Sep 14 '16 at 12:18
  • You shouldn't need to access elements from your controller. Just use `ng-model` or use `{{foo}}` in your HTML and `$scope.foo` in your controller, you can read/write to these variables from your controller. – Prateek Gupta Sep 14 '16 at 12:18
  • in angular way, you can better write a function which takes the parameter to find the correct object and returns it. – Asqan Sep 14 '16 at 12:20

2 Answers2

1

Try this

angular.forEach($scope.colors, function(color) {
    if(color.key === 3) {
        $scope.selectedColor = color;
    }
}

Then in the html view you can use this

{{selectedColor.color}}

If you want to do this in html side

<div ng-repeat="color in colors" ng-if="color.key===3">{{color.color}}</div>
Venkat
  • 265
  • 2
  • 17
1

Use can use

 angular.forEach($scope.colors, function(color, index){
      if(color.key ==3){
        $scope.requiredValue = color;
        $scope.requiredIndex =index;
      }

    })

and use

{{requiredValue.color}} Or {{colors[requiredIndex].color}}

nabin
  • 687
  • 4
  • 13