Create Shopping Cart with angularjs

 

In this Tutorial you will learn to build a shopping cart with angularjs . you can also integrate this Tutorial to your ecommerce app which we have created earlier here is the preview of our shopping cart

First off, we need to install the shopping cart directive. As in the previous Tutorial, we will install it with Bower. Open your terminal window at the project root and type the following command:

bower install ngcart --save
  • Now, open the app folder and edit the app.js file. Add the following highlighted code after the ngAside dependency:
    angular.module('interfacecomponents', [
      'ngResource',
      'ui.bootstrap',
      'ngCookies',
      'ngAnimate',
      'ngTouch',
      'ngSanitize',
      'ui.router',
      'ngAside',
      'ngCart'
    ])
  • Let’s create a ngCart controller. Go to modules/shared/directives/ and create a folder called ngcart. Inside this folder, create a file called ngcartCtrl.js and add the following code:
    'use strict';
    
    /**
     * @ngdoc function
     * @name app.controller:ShopCartCtrl
     * @description
     * # ShopCartCtrl
     * Controller of the app
     */angular.module('interfacecomponents')
    .controller('ShopCartCtrl', ['$scope', 'ngCart', '$http', function ($scope, ngCart, $http) {
    
      ngCart.setTaxRate(7.5);
       ngCart.setShipping(2.99);
    
    }]);

     

     

    • With the third step, we finished the installation process and initialization of ngCart. Let’s move on to the next steps. Edit the home.html file, remove the column layout with products, and place a new div with ShopCartCtrl. This is shown in the following code:
      <div ng-controller="ShopCartCtrl">
        <div class="row text-center">
          <div class="col-xs-6 col-sm-3">
            <img src="https://placehold.it/262x150" alt="image" />
            <h4>My Item #1</h4>
            <p> $10.99</p>
            <ngcart-addtocart id="item1" name="My Item #1" price="10.99" quantity="1" quantity-max="5">Add to Cart</ngcart-addtocart>
          </div>
          <div class="col-xs-6 col-sm-3">
            <img src="https://placehold.it/262x150" alt="image" />
            <h4>My Item #2</h4>
            <p> $15.29</p>
            <ngcart-addtocart id="item2" name="My Item #2" price="15.29" quantity="1" quantity-max="5">Add to Cart</ngcart-addtocart>
          </div>
            <div class="col-xs-6 col-sm-3">
            <img src="https://placehold.it/262x150" alt="image" />
            <h4>My Item #3</h4>
            <p> $25.75</p>
            <ngcart-addtocart id="item3" name="My Item #3" price="25.75" quantity="3" quantity-max="10">Add to Cart</ngcart-addtocart>
          </div>
          <div class="col-xs-6 col-sm-3">
            <img src="https://placehold.it/262x150" alt="image" />
            <h4>My Item #4</h4>
            <p> $29.25</p>
            <ngcart-addtocart id="item4" name="My Item #4" price="29.25" quantity="1" quantity-max="10">Add to Cart</ngcart-addtocart>
          </div>
        </div>
      </div>
    • Note that we replace the div from the previous example with the ngcart-addtocart directive on the highlighted code. Add the addtocart template at the end of home.html file:
      <script type="text/ng-template" id="template/ngCart/addtocart.html">
      <div ng-hide="attrs.id">
        <a class="btn btn-lg btn-primary" ng-disabled="true" ng-transclude></a>
      </div>
      <div ng-show="attrs.id">
        <div>
          <span ng-show="quantityMax">
            <select name="quantity" id="quantity" ng-model="q" ng-options=" v for v in qtyOpt"></select>
          </span>
            <a class="btn btn-sm btn-primary" ng-click="ngCart.addItem(id, name, price, q, data)" ng-transclude></a>
        </div>
        <span ng-show="inCart()">
        <br>
        <p class="alert alert-info">This item is in your cart. <a ng-click="ngCart.removeItemById(id)" style="cursor: pointer;">Remove</a></p>
        </span>
      </div>
      </script>

       

       

       

      • Go back to your terminal window and type the following command:
        grunt dev
        

        At this point, we will have an e-commerce layout with the ngcart directive:

      • Now we need to add the cart summary using the ngcart-summary directive. Add the following line after the shopcartctrl div controller:
        <div ng-controller="ShopCartCtrl">
        <div class="well text-center"><ngcart-summary></ngcart-summary></div>
        ...
      • Add the cart summary template at the end of home.html file, after the add to cart template:
        <script type="text/ng-template" id="template/ngCart/summary.html">
          <span class="">{{ ngCart.getTotalItems() }}
            <ng-pluralize count="ngCart.getTotalItems()" when="{1: 'item', 'other':'items'}"></ng-pluralize>
            <br />{{ ngCart.totalCost() | currency }}
          </span>
        </script>

        The previous operation will result in the following screenshot:

      • Let’s edit aside.html to include the cart itself. Inside the modal-body div, replace div alert with the following code:
        <div class="modal-body">
          <ngcart-cart></ngcart-cart>
        </div>
      • Add the cart template to the end of the aside.html file using the following code:
        <script type="text/ng-template" id="template/ngCart/cart.html">
        <div class="alert alert-warning" role="alert" ng-show="ngCart.getTotalItems() === 0">
          Your cart is empty
        </div>
        <div class="table-responsive col-lg-12" ng-show="ngCart.getTotalItems() > 0">
          <table class="table table-striped ngCart cart">
            <thead>
              <tr>
                <th></th>
                <th></th>
                <th>Quantity</th>
                <th>Amount</th>
                <th>Total</th>
              </tr>
            </thead>
            <tfoot>
              <tr ng-show="ngCart.getTax()">
                <td></td>
                <td></td>
                <td></td>
                <td>Tax ({{ ngCart.getTaxRate() }}%):</td>
                <td>{{ ngCart.getTax() | currency }}</td>
              </tr>
              <tr ng-show="ngCart.getShipping()">
                <td></td>
                <td></td>
                <td></td>
                <td>Shipping:</td>
                <td>{{ ngCart.getShipping() | currency }}</td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td>Total:</td>
                <td>{{ ngCart.totalCost() | currency }}</td>
              </tr>
            </tfoot>
            <tbody>
              <tr ng-repeat="item in ngCart.getCart().items track by $index">
                <td><span ng-click="ngCart.removeItemById(item.getId())" class="glyphicon glyphicon-remove"></span></td>
        
                <td>{{ item.getName() }}</td>
                <td><span class="glyphicon glyphicon-minus" ng-class="{'disabled':item.getQuantity()==1}"
                ng-click="item.setQuantity(-1, true)"></span>&nbsp;&nbsp;
                {{ item.getQuantity() | number }}&nbsp;&nbsp;
                <span class="glyphicon glyphicon-plus" ng-click="item.setQuantity(1, true)"></span></td>
                <td>{{ item.getPrice() | currency}}</td>
                <td>{{ item.getTotal() | currency }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        </script>

         

         

        1. The last action is to add the checkout functionality. Let’s add the template code to the end of aside.html, right after the cart template:
          <script type="text/ng-template" id="template/ngCart/checkout.html">
          <span ng-if="service=='http' || service == 'log'">
            <button class="btn btn-primary" ng-click="checkout()" ng-disabled="!ngCart.getTotalItems()" ng-transclude>Checkout</button>
          </span>
          </script>
        2. Replace the checkout bottom inside the modal-footer div on aside.html with the following code:
          <div class="modal-footer">
            <ngcart-checkout service="log">Checkout</ngcart-checkout>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
          </div>

          Now, let’s check the final result. Open your terminal window and type the following command:

          grunt dev
          

          How it works…

          We can see how to convert a static layout using custom directives. You can easily see this with the substitution of the code that creates the buttons to add the item to the shopping cart:

          <div id="item1" name="My Item #1" price="10.99" quantity="1" quantity-max="5">Add to Cart</div>
          <ngcart-addtocart id="item1" name="My Item #1" price="10.99" quantity="1" quantity-max="5">Add to Cart</ngcart-addtocart>

          This flexibility is provided by the ngCart directives. When we click on the Add to Cart button, the directive shows a simple message. This is shown in the following screenshot:


          It’s possible to add and remove a product using the directive’s add to cart function:
          <a class="btn btn-sm btn-primary"
            ng-click="ngCart.addItem(id, name, price, q, data)"
            ng-transclude></a>

          The products are stored using the local storage of your browser, which is the built in store service feature from directive:

          .service('store', ['$window', function ($window) {
          return {
          
          
            get: function (key) {
          
              if ($window.localStorage [key]) {
          
                var cart = angular.fromJson($window.localStorage [key]);
          
                return JSON.parse(cart);
          
              }
          
              return false;
          
          
            },
          
          
            set: function (key, val) {
          
          
              if (val === undefined) {
          
                $window.localStorage .removeItem(key);
          
              } else {
          
                 $window.localStorage [key] = angular.toJson(val);
          
              }
          
              return $window.localStorage [key];
          
              }
          
            }
          
          }])

          The following screenshot shows the result of clicking on the View Cart button:


          The Checkout button can perform three different tasks, including integration with PayPal. For this Tutorial, we just use $log.

          When we click on the Checkout button, the result for shopping cart can be found at the console panel of your browser, as we can see in the following screenshot:

          Note

          Note that the attribute data is empty just because we used a simple example to illustrate the directive functionality in an e-commerce application. On real applications, this contains an object with attributes from the item.

          There’s more…

          We can extend the directive and add more properties to our product just by editing the ngCart directive and by adding as many properties as we need:

          .directive('ngcartAddtocart', ['ngCart', function(ngCart){
            return {
              restrict : 'E',
              controller : 'CartController',
              scope: {
                id:'@',
                name:'@',
                quantity:'@',
                quantityMax:'@',
                price:'@',
                data:'='
            },
          ...

          Also, it’s possible to use a service to load the products list from a JSON file like this:

          [
            {
              "id": 01,
              "name": "Item 1",
              "price": 1900,
              "image": :"https://placehold.it/262x150"  
            },
            {
              "id": 02,
              "name": "Item 2",
              "price": 1000,
              "image": :"https://placehold.it/262x150"  
            },
            {
              "id": 03,
              "name": "Item 3",
              "price": 900,
              "image": :"https://placehold.it/262x150"  
            }
          ]

          Then, replace the cart items with the following code:

          <div class="col-xs-6 col-sm-3" ng-repeat=" item in products">
            <img src="{{item.image}}" alt="image" />
            <h4>{{item.name}}</h4>
            <p> ${{item.price}}</p>
            <ngcart-addtocart id="{{item.id}}" name="{{item.name}}" price="{{item.price}}" quantity="1" quantity-max="5">Add to Cart</ngcart-addtocart>
          </div>

           

          Applying custom CSS

          In this Tutorial, we will see how we can apply some CSS style to directives. In this special case, we will override the default Bootstrap CSS style, as we are building an e-commerce layout. Let’s see how to customize the Off Canvas menu directive.

          Getting ready

          How to do it…

          1. Inside the assets/css folder, create a file called style.css. Add the style.css code to the index.html file after the injector tag:
            <!-- injector:css -->
            <link rel="stylesheet" href="/src/bower_components/bootstrap/dist/css/bootstrap.css">
            <link rel="stylesheet" href="/src/bower_components/angular-aside/dist/css/angular-aside.css">
            <!-- endinjector -->
            <link rel="stylesheet" href="/app/assets/css/style.css">
          2. Place the following code into the style.css file:
            .modal-header {
              min-height: 16.42857143px;
              padding: 15px;
              border-bottom: 1px solid #B8B6B6;
              background-color: #EAEAEA;
              text-align: center;
            }
            
            .modal-body {
              position: relative;
              padding: 15px;
              background-color: #F4F4F4;
              min-height: 400px;
            }
            
            .modal-footer {
              padding: 15px;
              text-align: right;
              border-top: 1px solid #B8B6B6;
              background-color: #EAEAEA;
            
              position: absolute;
              bottom: 0px;
              width: 100%;
              text-align: center;
            }

            Now, the Off Canvas menu looks like this:

            How it works…

            We insert the link to the new stylesheet created in step 1, right after the injector tag. This is shown in the following example:

            <!-- injector:css →
            <!-- endinjector -->

            This is due to the fact that every time we run a task from Grunt.js, everything between the injector tag is replaced by the dependencies declared in our bower.json file.

            We just used three modal classes to apply the style. Also, we used the Bootstrap default class for alert-warning.

            There’s more…

            We can use custom CSS directly on Bootstrap internals using LESS files. To do that, follow the steps given earlier.

            You can find the Bootstrap modal files at the following path:

            Project Folder
            |-src/
            |--bower_components/
            |---bootstrap/
            |----less/
            |-----modal.less

            Here we use the variables of LESS to apply a new style to our modal:

            //== Modals
            //
            //##
            
            //** Padding applied to the modal body
            @modal-inner-padding:         15px;
            
            //** Padding applied to the modal title
            @modal-title-padding:         15px;
            //** Modal title line-height
            @modal-title-line-height:     @line-height-base;
            
            //** Background color of modal content area
            @modal-content-bg:                             #fff;
            //** Modal content border color
            @modal-content-border-color:                   rgba(0,0,0,.2);
            //** Modal content border color **for IE8**
            @modal-content-fallback-border-color:          #999;
            
            //** Modal backdrop background color
            @modal-backdrop-bg:           #000;
            //** Modal backdrop opacity
            @modal-backdrop-opacity:      .5;
            //** Modal header border color
            @modal-header-border-color:   #e5e5e5;
            //** Modal footer border color
            @modal-footer-border-color:   @modal-header-border-color;
            
            @modal-lg:                    900px;
            @modal-md:                    600px;
            @modal-sm:                    300px;

            The previous variables can be found at the root of the Bootstrap folder in a file called variables.less.

Deven Rathore

Deven is an Entrepreneur, and Full-stack developer, Constantly learning and experiencing new things. He currently runs CodeSource.io and Dunebook.com.

Published by
Deven Rathore
Tags: angularjscssgeekhtml5javajavascriptphp
5 years ago

Recent Posts

Flutter App Development: Essential Things You Should Know

Divided by mobile operating systems, companies have to develop their apps twice and roll them…

7 hours ago

7 Tips To Build Responsive & Dynamic Drupal Website For Your Business

For optimal user experience, consumers want responsive websites that are easy to use, multi-device friendly,…

2 days ago

OpenCart vs Magento: What You Should Choose in 2021

Users all over the world are faced with the problem of choosing a platform for…

1 week ago

Top 20 Android Open Source Projects

Reading codes and contributing to open source has been proven to be one of the…

3 weeks ago

Top 5 tools to proofread and edit essays with the help of software

Poor grammar and incorrect spelling can significantly lower the value of any literary work. Going…

7 hours ago

The Best 5 Career Advice for Web Design Students

Are you thinking of a career in web design but not sure where to start? The…

4 weeks ago