user3761308
user3761308

Reputation: 791

Pass Angular object property through variable?

Controller:

$scope.item = {"name": "b", "code": 3}
$scope.foo = "name";

How to access {{item.name}} through 'foo'?

This doesn't work:

HTML:

{{item.{{foo}}}}

Upvotes: 0

Views: 40

Answers (2)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Use square brackets to access the value of variable as a key of object. You are nesting the angular expression {{}} within another which is incorrect to access the value of key of the object.

angular.module('myApp', []).controller('personCtrl', function($scope) {
   $scope.item = {"name": "b", "code": 3}
   $scope.foo = "name";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="personCtrl">

  <p>{{item[foo]}}</p>

</div>

Upvotes: 0

plvice
plvice

Reputation: 458

Try this template HTML:

{{item[foo]}}

Upvotes: 1

Related Questions