Reputation: 2488
Suppose that I have an object like this:
var myObj = {
item1:{},
item2:{},
item3:{},
...
};
I also have another variable (e.g:itemHolder
) that could get values like item1
, item2
and so on.
I want to bind the object elements in my view. Is there any way to bind that according to the value of my variable? A solution like below:
{{myObj.[itemHolder]}}
Upvotes: 1
Views: 26
Reputation: 9800
Assuming that both variables are declared on your scope, yes, you can do it using javascript bracket notation like so:
$scope.myObj = {
item1: {},
item2: {},
item3: {},
...
};
$scope.itemHolder = 'item1';
Then you can interpolate the value like below:
{{ myObj[itemHolder] }} // {}
Working snippet:
angular.module('myApp', [])
.controller('AppController', function($scope) {
$scope.myObj = {
item1: { a: 1 },
item2: { b: 2 },
item3: { c: 3 }
};
$scope.itemHolder = 'item1';
});
<div ng-app="myApp" ng-controller="AppController">
Type the prop name<br>
<input type="text" ng-model="itemHolder"><br>
{{ myObj[itemHolder] }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
Upvotes: 2