To enable item removal from the shopping list, create a removeItem function in the controller that takes the item’s index as a parameter. In the HTML, add a <span> element for each item and use the ng-click directive to call removeItem with the current $index.
We can now remove items from our shopping list.
<script>
var app = angular.module(“myShoppingList”, []);
app.controller(“myCtrl”, function($scope) { $scope.products = [“Milk”, “Bread”, “Cheese”]; $scope.addItem = function () { $scope.products.push($scope.addMe); } $scope.removeItem = function (x) { $scope.products.splice(x, 1); } }); </script>
<div ng-app=”myShoppingList” ng-controller=”myCtrl”> |
Add the ability to remove items by creating a removeItem function in the controller, which takes the item’s index. In the HTML, use a <span> element with an ng-click directive that calls removeItem with the current $index.
A shopping list that allows for the display of error messages.
<script>
var app = angular.module(“myShoppingList”, []);
app.controller(“myCtrl”, function($scope) { $scope.products = [“Milk”, “Bread”, “Cheese”]; $scope.addItem = function () { $scope.errortext = “”; if (!$scope.addMe) {return;} if ($scope.products.indexOf($scope.addMe) == –1) { $scope.products.push($scope.addMe); } else { $scope.errortext = “The item is already in your shopping list.”; } } $scope.removeItem = function (x) { $scope.errortext = “”; $scope.products.splice(x, 1); } }); </script>
<div ng-app=”myShoppingList” ng-controller=”myCtrl”> |
The application works well but could use a more attractive design. To enhance its appearance, add the Code7.CSS stylesheet and apply the relevant classes throughout the application to match the shopping list example at the top of this page.
Style your application with the code7.CSS stylesheet.
<link rel=”stylesheet” href=”https://www.code7school.com/code7css/4/code7.css”> |