2015-07-18 24 views
0

我想在每次單擊添加按鈕時在AngularJS中動態添加表單輸入。但是,通過我擁有的代碼,輸入元素根本不顯示。我只是看到「發佈」按鈕。如果我刪除ng-repeat="ingredient in ingredients",表單顯示(如預期)。我在這裏做錯了什麼?ng-repeat導致表單元素不顯示

這裏是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}); 
    }; 
}]); 
+0

偉大工程在這裏。我剛剛在「ng-repeat」之外移動了添加按鈕。你有空陣列開始...所以沒有什麼可以重複和'add()'在裏面的中繼器http://plnkr.co/edit/x0cdBJ3aJTA5qK32wM3J?p=preview – charlietfl

+0

換句話說..沒有重複的意思是什麼都不會顯示。可以用'ng-show =「ingredients.length」'隱藏帖子按鈕 – charlietfl

回答

0

那是因爲你的按鈕在ng-repeat版元素。 ng-repeat在它被分配到的元素內重複HTML 。由於您在ingredients中沒有物品,因此不會顯示任何物品 - 包括您的按鈕

只需將您的按鈕從<div class="form-inline">中移出即可。

0

您的添加按鈕位於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>