Reputation: 1195
I'm creating an application where the user enters the name of a dish he/she ate as well as the calories for each dish (Right now, I'm just messing around with the name of the dish portion).
What I want to do is give the user 1 input :
Item 1 : ___________
Button[ADD MORE ITEMS]
And if the user clicks the button, it will add more rows of items.
Controller :
Meals = new Mongo.Collection("meals-info");
if (Meteor.isClient) {
var myApp = angular.module('calorie-counter',['angular-meteor']);
Meteor.subscribe('meals-info');
myApp.controller('formCtrl',['$scope','$meteor',function($scope,$meteor) {
$scope.allMeals = $meteor.collection(Meals);
$scope.meal = {
items:[]
};
$scope.addItem = function() {
$scope.meal.items.push({
name:null,
cal:null
});
}
}]);
}
Each meal has an items array that will represent the number of items the user has in his/her meal. Now in the view, I feel like the best way to go about it is to use the ng-repeat directive.
View:
<div id="left" ng-controller="formCtrl">
<div ng-repeat="???">
<label>Item {{$index+1}}
<input type="number" class="item" ng-model="???"><br>
<button ng-click="addItem()">Add More Items</button>
</label>
</div>
</div>
The portion with the '???' is the part I'm a little confused about. I'm a little unsure on how to go about things there in order to be able update the view w/another input field for an item and calories (Calorie has not been implemented yet, wanted to get the item portion correct first)
Upvotes: 0
Views: 148
Reputation: 8354
First, you'll want to move your button outside of the ng-repeat
unless you want the button displayed after each row.
Then, to iterate over the items in the meal, you'd populate your ng-repeat
with item in meal.items
. Your ng-model
(assuming the input is for "name") will be item.name
:
<div id="left" ng-controller="formCtrl">
<div ng-repeat="item in meal.items">
<label>Item {{$index+1}}
<input type="number" class="item" ng-model="item.name"><br>
</label>
</div>
<button ng-click="addItem()">Add More Items</button>
</div>
Upvotes: 1