我試圖在提交表單時創建包含「成分」數組及其屬性的「配方」對象。我使用ng-models創建了輸入:recipe.name,recipe.servings,recipe.ingredients [0] .name,recipe.ingredients [0] .amount,recipe.ingredients [1] .name,recipe.ingredients [1]。金額等,但是當表單被提交時,只會記錄recipe.ingredients [0]的屬性。在我的控制,我有以下幾點:如何在AngularJS中使用來自表單的對象數組創建對象
angular.module('recipeMavenApp')
.controller('AddRecipeCtrl', function() {
var vm = this;
vm.ingredientCount = 1;
vm.recipe = {
name: '',
servings: 0,
ingredients: [],
};
vm.appendIngredient = function() {
var newIngredientInput = angular.element('<input type="text"' +
'ng-model="recipe.ingredients[' + vm.ingredientCount + '].name" placeholder="Ingredient name" />' +
'<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[' +
vm.ingredientCount + '].amount" placeholder="Amount"/>');
angular.element(document.querySelector('#ingredients')).append(newIngredientInput);
vm.ingredientCount++;
};
vm.addRecipe = function(recipe) {
vm.recipe = recipe;
console.log(vm.recipe); //Testing to see what is received.
};
形式:
<form novalidate >
<div class="form-group">
<label for="recipeName">Name of Recipe</label>
<input type="text" ng-model="recipe.name" id="recipeName" required/>
</div>
<div class="form-group">
<label for="recipeServings">Number of Servings</label>
<input type="number" min="1" max="50" ng-model="recipe.servings" id="recipeServings"/>
</div>
<div class="form-group" id="ingredients">
<label for="recipeIngredients">Ingredients</label>
<button class="btn btn-primary btn-xs" ng-click="add.appendIngredient()">Add Ingredient</button>
<br />
<input type="text" ng-model="recipe.ingredients[0].name" id="recipeIngredients" placeholder="Ingredient name" />
<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[0].amount" placeholder="Amount"/>
<br/>
</div>
<button ng-click="add.addRecipe(recipe)" class="btn btn-primary"><span class="glyphicon glyphicon-share"></span> Add Recipe</button>
</form>
如何捕捉形式recipe.ingredients陣列中的所有成分提交?
你能不能添加一些html?更好,一個jsfiddle? – Derlin
爲什麼大家總是想要一個小提琴?這似乎並不難調試。但你確實需要向我們展示形式,而不是爲此負責。 –