trying to learn
trying to learn

Reputation: 129

AngularJS ng-repeat in two dimensional array

I want to use ng-repeat inside div like this :

<li ng-repeat="image in HomeCtrl.images.data" >
    <a ng-href="@{{ image.code }}"><img ng-src="@{{ image.url }}" ></a>
</li>

Here is images array :

{
  "data": {
    "url": [
      "https://url1.com",
      "https://url2.com"
    ],
    "code": [
      "3cs14vs4",
      "512631va"
    ]
  }
}

images array is inside HomeCtrl

Upvotes: 0

Views: 1842

Answers (2)

J-Mean
J-Mean

Reputation: 1200

Please find following working snippet.

(function(angular) {
  'use strict';
angular.module('app', [])
  .controller('ExampleController', ['$scope', function($scope) {
    //Change your Json Object
    $scope.images = { 
   "data":[
     {"url":  "https://url1.com","code":"3cs14vs4"},
     {"url":  "https://url2.com","code":"512631va"}
   ],
}  
    
    
    
 }]);
})(window.angular);
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
  
</head>
<body ng-app="app">
  <div ng-controller="ExampleController">  
  
 <ul>
 <li ng-repeat="image in images.data" >
    <a ng-href="{{ image.code }}"><img ng-src="{{ image.url }}" ></a>
</li>
</ul>
    
</div>
</body>
</html>

Note: Had changed your object data structure.

Upvotes: 1

Yossi Neiman
Yossi Neiman

Reputation: 825

You should do it in a view that is already assigned to the controller, If your in a different controller you can do something like that:

<ul ng-conroller="HomeCtrl">
  <li ng-repeat="image in images.data.url track by $index" >
    <a ng-href="{{ images.data.code[$index] }}">
       <img ng-src="{{ image.data.url[$index] }}" >
    </a>
  </li>
</ul>
  • Keep in mind that the order of the element should be in sync

Aside from your question I think a better data structure should be as following:

{
 {"code": "xx", "url": "yyy"},
 {"code": "xx", "url": "yyy"},
 {"code": "xx", "url": "yyy"},
 ....
}

Upvotes: 2

Related Questions