Reputation: 680
I'm new to Angular. I have a form in an ordered list. When a user inputs a value in the form and clicks "add", I'd like the value from the form to replace the form, and another list item added below with the same form allowing the user to add another item, etc., etc.
Below is what I've got so far. I have the ordered list with form input, but right now when you click "add", the item appears below as a separate list item instead of replacing the form. I'd like it to replace the form, then insert a new list item below with the same form so the user can continue to add items to the list in this manor.
items.html
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="items.js"></script>
</head>
<body>
<h2>Items</h2>
<div ng-controller="ItemCtrl">
<ol>
<li>
<form ng-submit="addItem()">
<input type="text" ng-model="itemText" size="30"
placeholder="add new item to list">
<input class="btn-primary" type="submit" value="add">
</form>
</li>
<li ng-repeat="item in items">
<span>{{item.text}}</span>
</li>
</ol>
</div>
</body>
</html>
items.js
function ItemCtrl($scope) {
$scope.items = [];
$scope.addItem = function() {
$scope.items.push({text:$scope.itemText});
$scope.itemText = '';
};
}
How do I get that to work as described?
Thanks
Upvotes: 1
Views: 1380
Reputation: 230
I edited your fiddle:
I believe if you just place the ng-repeat of items above the form you will achieve the desired behavior.
<li ng-repeat="item in items">
<span>{{item.text}}</span>
</li>
<li>
<form ng-submit="addItem()">
<input type="text" ng-model="itemText" size="30"
placeholder="add new item to list">
<input class="btn-primary" type="submit" value="add">
</form>
</li>
Upvotes: 0
Reputation: 10673
Looks like you just need to switch the form and ng-repeat directive.
Like so:
<div ng-controller="ItemCtrl">
<ol>
<li ng-repeat="item in items">
<span>{{item.text}}</span>
</li>
<li>
<form ng-submit="addItem()">
<input type="text" ng-model="itemText" size="30"
placeholder="add new item to list">
<input class="btn-primary" type="submit" value="add">
</form>
</li>
</ol>
</div>
Upvotes: 2