简体   繁体   中英

Populate table with data from json using dropdowns

I'm making a little web app project with bus time tables. I'm trying to populate table with data from json using dropdowns. I don't know if I'm doing the json part right, but I'm stuck with parsing data so that the table would show the correct times for selected bus and stop.

It has to go like this: select bus number, select bus stop, then correct times appear below in the table.

HTML select part:

Bus No.: <select ng-model="selectedNr" ng-options="x for (x,y) in busData"></select>

Stop name: <select ng-model="selectedStop" ng-options="x for (x,z) in selectedNr.stops"></select>

Then the table:

<table class="time-table">
  <tr ng-repeat="time in busData[selectedNr].stops[selectedStops].time">
    <th>{{time.hour}}</th>
    <td ng-repeat="minute in time.minutes">{{minute}}</td>
  </tr>

Angular part:

app.controller("ngCtrl", function ($scope) {
"use strict";
$scope.busData = {
   "bus1":{
       "id":1,
       "stops":{
           "stop1":{
               "id":1,
               "stopName":"stop1",
               "time":[
                   {
                       "hour": 1,
                       "minutes": [11, 21,31,41,51]
                   },
                   {
                       "hour": 2,
                       "minutes": [12, 22,32,42,52]
                   }
               ]


           },
            "stop2":{
               "id":2,
               "stopName":"stop2",
               "time":[
                   {
                       "hour": 3,
                       "minutes": [11, 21,31,41,51]
                   },
                   {
                       "hour": 4,
                       "minutes": [12, 22,32,42,52]
                   }
               ]

           }
       }
   }, (and so on...)

Embeded Plunker

When you select a bus, the SelectedNr is not the index of the selected element but the whole sub-element in the array so you don't need to ng-repeat for each busData[selectedNr] but just for each selectedNr .

Here is a corrected version of the main part in your HTML. There is nothing to change with your JSON.

<main class="content">
    <section class="filter-wrapper">
        <h2>Bus No.:
        <span><select ng-model="selectedNr" ng-options="x for (x,y) in busData"></select></span>
        </h2>
        <h4>Stop name: <span><select ng-model="selectedStop" ng-options="x for (x,z) in selectedNr.stops"></select></span>
        </h4>
    </section>
    <table class="time-table">
        <tr ng-repeat="time in selectedStop.time">
            <th>{{time.hour}}</th>
            <td ng-repeat="minute in time.minutes">{{minute}}</td>
        </tr>
    </table>
</main>

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