2016-05-13 42 views
0

我有一個我試圖顯示的對象數組。問題是我只能通過它的屬性名稱來訪問數據。我想要迭代使用對象的關鍵。ng-repeat對象數組(使用ng-start)

該對象有兩個屬性,每個屬性表示一個開始時間和一個結束時間。他們將被顯示在每個單元格中。

我的表的結構是這樣的:

<table class="table table-striped"> 
    <tr> 
     <th></th> 
     <th ng-repeat="department in departments" style="vertical-align:top" colspan="2">{{department}}</th> 
    </tr> 
    <tr ng-repeat="time in times"> 
     <td>{{weekdays[$index]}}</td> 
     <td ng-repeat-start="dept in time">{{times[$index].service.start}}</td> 
     <td ng-repeat-end>{{times[$index].service.end}}</td> 
    </tr> 
</table> 

在這種情況下,我怎麼能動態訪問的對象?

我的控制器:

.controller("businessHours", function($scope) { 
    $scope.weekdays = ["Sunday", "Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]; 
    $scope.departments = ["sales", "service","accounting","bodyshop","other","parts"]; 

    $scope.times = []; 
    $.each($scope.weekdays, function(index, value) { 
    var dayTimes = {}; 
    $.each($scope.departments, function(index2, value){ 
     console.log(index) 
     dayTimes[value] = {start: '5', end: '6'}; 
    }); 
    $scope.times.push(dayTimes); 
    }); 


}) 

我要對這個正確或是否有更好的方式來安排我的數據結構?

回答

1

遍歷在(key,value) in ng-repeat角:

瞭解更多關於ng-repeat

<div ng-repeat="(key, value) in myObj"> ... </div>

在你的情況,更新HTML其中:

<td ng-repeat-start="(key,dept) in time">{{times[$index][key].start}}</td> 
<td ng-repeat-end>{{times[$index][key].end}}</td> 

angular.module('app', []) 
 
    .controller('homeCtrl', function($scope) { 
 
    $scope.weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; 
 
    $scope.departments = ["sales", "service", "accounting", "bodyshop", "other", "parts"]; 
 

 
    $scope.times = []; 
 
    angular.forEach($scope.weekdays, function(v, i) { 
 
     var dayTimes = {}; 
 
     angular.forEach($scope.departments, function(value, index) { 
 
     console.log(index) 
 
     dayTimes[value] = { 
 
      start: '5', 
 
      end: '6' 
 
     }; 
 
     }); 
 
     $scope.times.push(dayTimes); 
 
    }); 
 
    console.info($scope.times); 
 
    });
td,tr { 
 
    text-align:center; 
 
    min-width: 20px; 
 
}
<html> 
 

 
<head> 
 
    <title>Single Demo</title> 
 
    <script src="//cdn.bootcss.com/jquery/2.2.1/jquery.js"></script> 
 
    <script src="//cdn.bootcss.com/angular.js/1.4.7/angular.js"></script> 
 

 
</head> 
 

 
<body ng-app="app" ng-controller="homeCtrl"> 
 
    <div class="container"> 
 
    <table class="table table-striped"> 
 
     <tr> 
 
     <th></th> 
 
     <th ng-repeat="department in departments" style="vertical-align:top" colspan="2">{{department}}</th> 
 
     </tr> 
 
     <tr ng-repeat="time in times"> 
 
     <td>{{weekdays[$index]}}</td> 
 
     <td ng-repeat-start="(key,dept) in time">{{times[$index][key].start}}</td> 
 
     <td ng-repeat-end>{{times[$index][key].end}}</td> 
 
     </tr> 
 
    </table> 
 
    </div> 
 
</body> 
 

 
</html>

+0

非常感謝。獲得的教訓是更多地參考文檔。 – o6t9o