我有这样的数据模型:
$scope.meals = [
{
name: 'breakfast',
days: [
{
name: 'monday'
},
{
name: 'sunday'
}
]
},
{
name: 'lunch',
days: [
{
name: 'saturday'
},
{
name: 'sunday'
}
]
},
{
name: 'dinner',
days: [
{
name: 'friday'
}
]
}
];
我想为object中的所有选项生成<tr>
,如下所示:
<tr>
<td>breakfast - monday</td>
</tr>
<tr>
<td>breakfast - sunday</td>
</tr>
<tr>
<td>lunch - saturday</td>
</tr>
<tr>
<td>lunch - sunday</td>
</tr>
等
我该怎么做?嵌套<tr>
是不可能的,我不知道如何使用ng-repeat
。
答案 0 :(得分:1)
您可以使用template / tbody标签,您根本不需要更改数据结构:
示例:在Angular2中,您可以使用
<template ngFor #meal [ngForOf]="meals">
<tr ngFor="#day of meal.days">
<td>{{ meal.name }} - {{ day }}</td>
</tr>
</template>
示例:在Angular1中:( AFAIK,在单个表中可以有多个<tbody>
。)
<tbody ng-repeat="meal in meals">
<tr ng-repeat="day in meal.days">
<td>{{ meal.name }} - {{ day }}</td>
</tr>
</tbody>
答案 1 :(得分:0)
您的数据结构不适合ng-repeat
首先,适应它:
$scope.mealsList = $scope.meals.reduce(function(mealArray, meal) {
meal.days.forEach(function (day) {
mealArray.push({ name: meal.name, day: day.name });
});
return mealArray;
}, []);
// result:
// [{name: 'breakfast', day: 'monday' }, {name:'breakfast', day:'monday' }...]
然后在模板中使用ng-repeat作为经典:
<tr ng-repeat="meal in mealsList">
<td>{{ meal.name }} - {{ meal.day }}</td>
</tr>
如果您编辑原始数据模型,您将无法看到适应数据模型中的更改。
你可以用这种方式规避:
<button ng-click="addMeal()">Add Another meal</button>
然后在你的控制器内:
function addMeal() {
$scope.meals.push({}); // add data in your own way
$scope.mealsList = adaptMeals($scope.meals);
}
这会在每次添加新餐时重新构建mealsArray
,并且完全没问题,除非您的膳食阵列包含50.000+元素;)
答案 2 :(得分:0)
您可以根据需要使用forEach
格式化数组,并将其与ng-repeat
var app = angular.module('app', []);
app.controller('TestController', function($scope) {
var mealsData = [
{
name: 'breakfast',
days: [
{
name: 'monday'
},
{
name: 'sunday'
}
]
},
{
name: 'lunch',
days: [
{
name: 'saturday'
},
{
name: 'sunday'
}
]
},
{
name: 'dinner',
days: [
{
name: 'friday'
}
]
}
];
var meals = [];
mealsData.forEach(function(meal) {
if(meal && meal.days) {
meal.days.forEach(function(day) {
meals.push({name: meal.name, day: day.name});
});
}
});
$scope.meals = meals;
});
angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-controller="TestController">
<tr ng-repeat="meal in meals">
<td>{{meal.name + ' - ' + meal.day}}</td>
</tr>
</table>
答案 3 :(得分:0)
您可以使用ng-repeat-start
和ng-repeat
:但是会有epmty tr
标记
<table >
<tr ng-repeat-start="meal in meals" ng-if="meal.close"></tr>
<tr ng-repeat-end ng-repeat="day in meal.days">
<td>{{meal.name}} - {{day.name}}</td>
</tr>
</table>