0

I have this list with a key,value structure that stores the data coming from a JSON structure and I want to print this data in a table with an ng-repeat.

var data = [
          {
            id: 1,
            name : "Peter",
            lastname : "Smith",
            age : 36
          }, {
            id: 2,
            name : "Peter",
            lastname : "Smith",
            age : 36
          }
        ];

        $scope.itemDictionary = {};
        angular.forEach(data, function(item){
            var obj = {};
            var valObj = {};

            valObj.name = item.name;
            valObj.lastname = item.lastname;
            valObj.age = item.age;

            obj[item.id] = valObj;
            if(!$scope.itemDictionary[item.id]){
                 $scope.itemDictionary[item.id] = obj;
            }
        });

I know that it should be ng-repeat="d in something" inside a table but I dont know how to achive this based on the structure that I have.

0

2 Answers 2

1

Use ng-repeat="(key,value) in itemDictionary"

<div ng-app="exampleApp">
    <div ng-controller="ExampleController">

        {{itemDictionary}}

        <div ng-repeat="(key,value) in itemDictionary track by key">
            <h1>ID: {{key}}</h1>
            <h1>Name: {{value[$index + 1].name}}</h1>
            <h1>Lastname: {{value[$index + 1].lastname}}</h1>
            <h1>Age: {{value[$index + 1].age}}</h1>
        </div>

    </div>
</div>

example: http://codepen.io/gpincheiraa/pen/vGoqzr

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your time.
@kennechu U're welcome. If this answer helped to solve your problem, marks as correct answer for future visits to this thread.
1

I don't know but why are you using so much unnecessary hashes. you can just simply assign your json data to any scope variable and then use it in view. Example -:

//inside controller...
 var data = [
      {
        id: 1,
        name : "Peter",
        lastname : "Smith",
        age : 36
      }, {
        id: 2,
        name : "Peter",
        lastname : "Smith",
        age : 36
      }
    ];

   $scope.itemDictionary = data;


 //inside view...

<table>
 <tr id="{{item.id}}" ng-repeat="item in itemDictionary">
   <td>{{item.id}}</td>   
   <td>{{item.name}}</td>
   <td>{{item.lastname}}</td>
   <td>{{item.age}}</td>
 </tr>
</table>

that's it... :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.