Vivien Pipo Vivien Pipo - 5 months ago 39
AngularJS Question

Angularjs ng-repeat use key as property name of an obj

In angular, I would like to use key of a ng-repeat as a property name of an obj

$scope.datas= {};
$scope.datas.key1 = 'val1';
$scope.datas.key2 = 'val2';


$scope.dictionnary= {};
$scope.dictionnary['key1'] ='toto';
$scope.dictionnary['key2'] ='titi';


<div ng-repeat="(key, value) in datas">
{{dictionnary[key]}} //does not work!
</div>


Do you know hot to do this?

Answer

Ok so it may come down to a few things:

1: you can use datas also as a dictionary and then it would work with 1 loop (PICK ME)

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.datas = {};
    $scope.datas.key1 = 'val1';
    $scope.datas.key2 = 'val2';


    $scope.dictionnary = {};
    $scope.dictionnary['key1'] = 'toto';
    $scope.dictionnary['key2'] = 'titi';
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myController">
    <div ng-repeat="(key, value) in datas">
      {{dictionnary[key]}} //does not work!
    </div>
  </div>
</div>

2: you can use nested ng-repeat like @Omri Aharon showed