Я пытаюсь динамически добавлять ввод формы в AngularJS при каждом нажатии кнопки добавления. Однако, с кодом, который у меня есть, это элементы ввода вообще не отображаются. Я просто вижу кнопку "Опубликовать". Если я удалю ng-repeat="ingredient in ingredients"
, форма отобразится (как и ожидалось). Что я здесь делаю неправильно?
Вот конкретный код в index.ejs:
<form ng-model="recipe">
<div class="form-inline" ng-repeat="ingredient in ingredients">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" ng-model="ingredient.name"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Quantity" ng-model="ingredient.quantity"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Unit" ng-model="ingredient.unit"></input>
</div>
<div class="form-group">
<button type="button" id="add" ng-click="add()">Add</button>
</div>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
Вот соответствующий js-код:
app.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
$scope.ingredients = [];
$scope.add = function() {
var newItemNo = $scope.ingredients.length+1;
$scope.ingredients.push({'id':'choice'+newItemNo});
};
}]);
Это потому, что ваша кнопка находится в элементе ng-repeat
ed. ng-repeat
повторяет HTML внутри элемента, которому он назначен. Поскольку у вас нет элементов в ingredients
, ничего не отображается - включая вашу кнопку
Просто переместите свою кнопку из <div class="form-inline">
.
Ваша кнопка добавления находится внутри ng-repeat, поэтому она никогда не отображается, поэтому вы никогда не сможете заполнить массив, чтобы он никогда не отображался. Имеет ли это смысл?
Пытаться
<form ng-model="recipe">
<div class="form-inline" ng-repeat="ingredient in ingredients">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" ng-model="ingredient.name"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Quantity" ng-model="ingredient.quantity"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Unit" ng-model="ingredient.unit"></input>
</div>
</div>
<div class="form-group">
<button type="button" id="add" ng-click="add()">Add</button>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
ng-repeat
. У вас есть пустой массив для запуска ... так что нечего повторять иadd()
внутри повторителя plnkr.co/edit/x0cdBJ3aJTA5qK32wM3J?p=previewng-show="ingredients.length"