Joe82 Joe82 - 2 months ago 5
AngularJS Question

AngularJS - calling a element in an array when I don't know its exact position

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!

Answer

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>
Comments