E-Madd
E-Madd

Reputation: 4572

How to bind template to object in array by property value?

I'm probably looking for a directive of some sort, right?

//JS
$rootScope.cats = [
         { sort:0, value:'ABY', label:'Abyssinian' },
         { sort:1, value:'RGD', label:'Ragdoll' },
         { sort:2, value:'RBL', label:'Russian Blue' },
         { sort:3, value:'OCT', label:'Ocicat' }
];

//HTML

{{cats['ABY'].label}} //This obviously doesn't work.  Is there something in Angular that would?

Upvotes: 0

Views: 63

Answers (2)

Kath
Kath

Reputation: 1854

Try to find the proper object in controller, for example:

$scope.cats = [
 { sort: 0, value: 'ABY', label: 'Abyssinian' },
 { sort: 1, value: 'RGD', label: 'Ragdoll' },
 { sort: 2, value: 'RBL', label: 'Russian Blue' },
 { sort: 3, value: 'OCT', label: 'Ocicat' }
];

$scope.selectedCat = _.find($scope.cats, function (cat) {
    return cat.value == 'OCT';
});

And put this into your layout:

{{selectedCat.label}}

NB Lodash library is used to find the proper cat.

Upvotes: 1

dmahapatro
dmahapatro

Reputation: 50245

This can be a candidate for a custom filter. See DEMO

app.filter('label', function(){
  return function(arr, value) {
    var cats;

    if(arr) {
      cats = arr.filter(function(elem) {
        return elem.value == value;
      });
    }

    return cats && cats.length > 0 ? 
              cats[0].label : 'Not Found';
  }
});

Upvotes: 0

Related Questions