我正在尝试制作饮食形式。它有很多天,吃的类型和产品。我将使用codepen中的代码来解释问题。我使用ngRepeat创建多个选择表单:
<select ng-repeat="row in rows track by $index" ng-options="product as product.label for product in products" ng-model="diet[0].products[$index]"></select>
what.products被视为一个对象,而不是一个对象数组:
[ { "type": "breakfast", "time": "9:00", "products": { "0": { "label": "Apples", "value": 4, "id": 2 }, "1": { "label": "Apples", "value": 4, "id": 2 } } } ]
HTML:
<html ng-app="myApp">
<body>
<div ng-controller="MyCtrl" ng-init="diet[0].type='breakfast'; diet[0].time='9:00'">
<input type="text" ng-model="diet[0].type">
<input type="text" ng-model="diet[0].time">
<select ng-repeat="row in rows track by $index" ng-options="product as product.label for product in products" ng-model="diet[0].products[$index]"> </select>
<p> {{ selected | json }} </p>
<p> {{ diet | json }} </p>
</div>
</body>
</html>
MyCtrl.js
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.rows=[{},{}];
$scope.products = [
{ label: "Apples", value: 4, id: 2 },
{ label: "Oranges", value: 2, id: 1 },
{ label: "Limes", value: 4, id: 4 },
{ label: "Lemons", value: 5, id: 3 }
];
$scope.diet = [];
}]);
我不能将diet.products初始化为一个阵列因为饮食有很多天和饮食类型。这样做只适用于0索引数组:
$scope.diet[0].products = [];
简单codepen示例。
编辑:完整的饮食创建形式如下所示:您输入饮食的日子,例如10,您可以使用10个标签。每个标签表示一天,包含所有这6种饮食类型(早餐,午餐,晚餐等)。接下来,您有6个吃饭类型表,例如this one,您可以通过在输入字段中输入并指定数量来添加产品。每天和每种饮食类型可能都有独特的产品。
EDIT2:我想做到这一点,你可以一次性创造饮食。这不是单页应用程序。我在后端使用laravel。
EDIT3: 饮食js 期望的结构
[
{
"day":1,
"eating_types":[
{"type":"Breakfast","time":"8:00", "products":[]},
{"type":"Lunch","time":"12:00", "products":[]}
]
},
{
"day":2,
"eating_types":[
{"type":"Breakfast","time":"8:00", "products":[]},
{"type":"Lunch","time":"12:00", "products":[]}
]
},
]
答案 0 :(得分:1)
所以假设你有一些用户输入天数/饮食/无论什么的东西。当您处理该输入时,为什么不完全初始化您的diet
数组
let numberOfDays = 10; // for example, this would come from the user
let diet = Array.apply(null, {length: numberOfDays}).map((tmp, n) => ({
day: n + 1,
eating_types: [
{type: "Breakfast", time: "8:00", products: []},
{type: "Lunch", time: "12:00", products: []}
]
}));
console.log(diet);