ng-repeat 一组对象(使用 ng-start)

ng-repeat over an array of objects (using ng-start)

我有一组要显示的对象。问题是我只能通过使用 属性 名称调用数据来访问数据。我想通过使用对象的键进行迭代。

该对象有两个属性,每个 属性 代表一个开始时间和一个结束时间。它们将显示在每个单元格中。

我的 table 结构如下:

<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);
  });


})

我这样做是否正确,或者是否有更好的方法来安排我的数据结构?

遍历 angular 中的 (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>