简体   繁体   中英

Looping through an object and displaying input fields

I have a javascript object that consists of two arrays. We can call one array adaptors and the other barcodes. The adaptors array will always have 8 strings, while the barcodes will always have 3 strings but may have up to 8 strings. Ok, so I need to display the adaptor string, the barcode string and than have a input field for the user to enter another string(barcode). However, I need to find the length of the barcodes array and than only display that many input fields. What would be the easiest way to accomplish this? jQuery, Angular?

var bar = {
    “adaptors”: ["506-707", "502-701", "501-708", "507-706", "508-704", "505-703", "503-705", "504-702" ],
    “barcodes”:["11-11-1111","11-11-2222","11-11-3333","11-11-4444"]
}

在此处输入图片说明

try this angularJS code, here is working fiddle

view

<div ng-controller="MyCtrl">
<div ng-repeat="(index,val) in bar.adaptors">
 {{val}} <input type="text" ng-show="bar.barcodes[index]">
</div>
</div>

controller

var myApp = angular.module('myApp',[]);

 function MyCtrl($scope) {
   $scope.bar = {
      adaptors: ["506-707", "502-701", "501-708", "507-706", "508-704", "505-703", "503-705", "504-702" ],
    barcodes:["11-11-1111","11-11-2222","11-11-3333","11-11-4444"]
 }
}

Assuming each adaptor correlates with each barcode meaning adaptors[0] lines up with barcodes[0] :

You can use an ng-repeat with (index,value) and use index or use the auto generated $index value that is set each iteration to access the bar.barcodes element. Use ng-if to only generate the input if the array element exists.

 angular.module('app',[]).controller("ctrl",["$scope",function($scope){ $scope.bar = { "adaptors": ["506-707", "502-701", "501-708", "507-706", "508-704", "505-703", "503-705", "504-702" ], "barcodes":["11-11-1111","11-11-2222","11-11-3333","11-11-4444"] }; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <table ng-app="app" ng-controller="ctrl"> <tr ng-repeat="adaptor in bar.adaptors"> <th>Adaptor</th><td>{{adaptor}}</td> <th>Barcode</th><td> <input ng-if="bar.barcodes[$index]" ng-model="bar.barcodes[$index]"> </td> </tr> </table> 

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