如何在AngularJS中拥有一个带有表单对象数组的对象

时间:2016-02-19 18:29:37

标签: angularjs

我试图制作一个'配方'包含一系列成分的对象'提交表单时的属性和属性。我用ng-models创建了输入:recipe.name,recipe.servings,recipe.ingredients [0] .name,recipe.ingredients [0] .amount,recipe.ingredients [1] .name,recipe.ingredients [1]。但是,当提交表单时,只记录recipe.ingredients [0]的属性。在我的控制器中,我有以下内容:

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数组中的所有成分?

1 个答案:

答案 0 :(得分:1)

我尝试在那里重写您的代码:JSFiddle

我使用ng-repeat生成成分列表(我在模型中使用$index)以避免控制器中的任何DOM操作:

<div ng-repeat="ingredient in recipe.ingredients">
  <input type="text" ng-model="recipe.ingredients[$index].name" placeholder="Ingredient name" />
  <input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[$index].amount" placeholder="0"/> 
</div>

基于模型:

$scope.recipe = {
  name: '',
  servings: 0,
  ingredients: [{
    name: '',
    amount: null
  }]
};

$scope.recipe.ingredients中,您可以默认添加需要显示的{name:'', amount:null}个数量(您还可以添加预填充的名称或金额,例如:{name:'Ingredient 1', amount:5})。

然后,当我需要一种新成分时,我只需在$scope.ingredients数组中推送一个新对象:

$scope.appendIngredient = function() {
  $scope.recipe.ingredients.push({
    name: '',
    amount: null
  });
};

如果满足您的要求或有任何疑问,请随时告诉我。

由于