angularjs shopping cart application Example

Posted by w3diy - 7 months ago

Lets use some of the AngularJS features to make a shopping list, where you can add or remove items:

<!DOCTYPE html>
<script src=""></script>
<link rel="stylesheet" href="">

var app = angular.module("myShoppingList", []); 
app.controller("myCtrl", function($scope) {
    $scope.items = ["Milk", "Bread", "Cheese"];
    $scope.addItem = function () {
        $scope.errortext = "";
        if (!$scope.addMe) {return;}
        if ($scope.items.indexOf($scope.addMe) == -1) {
        } else {
            $scope.errortext = "The item is already in your shopping list.";
    $scope.removeItem = function (x) {
        $scope.errortext = "";    
        $scope.items.splice(x, 1);

<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrl" class="w3-card-2 w3-margin" style="max-width:400px;">
  <header class="w3-container w3-light-grey w3-padding-16">
    <h3>My Shopping List</h3>
  <ul class="w3-ul">
    <li ng-repeat="x in items" class="w3-padding-16">{{x}}<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span></li>
  <div class="w3-container w3-light-grey w3-padding-16">
    <div class="w3-row w3-margin-top">
      <div class="w3-col s10">
        <input placeholder="Add shopping items here" ng-model="addMe" class="w3-input w3-border w3-padding">
      <div class="w3-col s2">
        <button ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button>
    <p class="w3-text-red">{{errortext}}</p>