简体   繁体   中英

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

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"},
 ....
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM