Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

Step 3. Removing Items:

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.

Example

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”>
  <ul>
    <li ng-repeat=”x in products”>
      {{x}}<span ng-click=”removeItem($index)”>&times;</span>
    
</li>
  </ul>
  <input ng-model=”addMe”>
  <button ng-click=”addItem()”>Add</button>
</div>

Step 4. Error Handling:

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.

Example

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”>
  <ul>
    <li ng-repeat=”x in products”>
      {{x}}<span ng-click=”removeItem($index)”>&times;</span>
    </li>
  </ul>
  <input ng-model=”addMe”>
  <button ng-click=”addItem()”>Add</button>
  <p>{{errortext}}</p>
</div>

Step 5. Design:

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.

Example

Style your application with the code7.CSS stylesheet.

<link rel=”stylesheet” href=”https://www.code7school.com/code7css/4/code7.css”>