Archie Archie - 5 months ago 11
AngularJS Question

Can't add item via Angular 1.x

Just started to learn Angular. I try to make a simple shopping list app, but 'Add' button doesn't work.
When I press it (

ng-submit="addItem()"
) nothing happen. Apparently
$scope.addItem
doesn't work correctly.



var myModule = angular.module('list', []);
myModule.controller('ListCtrl', ListCtrl);

function ListCtrl($scope) {
$scope.items = [
{ text: 'Chocolate', done: true },
{ text: 'Potato', done: false },
{ text: 'Banana', done: false },
{ text: 'Water', done: true }
];

$scope.addItem = function () {

$scope.items.push({ text: $scope.itemText, done: false });
$scope.itemText = '';
};

$scope.remain = function () {
var count = $scope.items.length;

angular.forEach($scope.items, function(item) {
count -= item.done;
});
return count;
};
}

.list{
width: 400px;
margin: 0px auto;
}

.done-true {
text-decoration: line-through;
color: grey;
}
.done-false {
text-decoration: underline;
color: red;
}

<html lang="en" ng-app="list">
<head>
<title>Document 1</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">

</head>
<body>

<div class="list">
<h2>Shopping List</h2>
<div class="panel" ng-controller="ListCtrl">
<span>{{remain()}} item(s) left to buy of {{items.length}}</span>
<table class="table table-striped">
<tbody>
<tr ng-repeat="item in items">
<td><input class="checkbox-inline" type="checkbox" ng-model="item.done"></td>
<td><span class="done-{{item.done}}">{{item.text}}</span></td>
</tr>
</tbody>
</table>
</div>

<form ng-submit="addItem()">
<input class="form-control" type="text" ng-model="itemText" size="30" placeholder="Add item to list">
<input class="btn btn-primary" type="submit" value="Add">
</form>
</div>
</body>
</html>





http://codepen.io/ArkadiyS/pen/BzWjvX

Answer

Check your code and make sure your <form> should be inside your <div class="panel" ng-controller="ListCtrl">.