[英]ng-repeat causes form elements to not display
我試圖每次單擊添加按鈕時在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
元素中。 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.