Using Angularjs and bootstrap to realize shopping cart function _angularjs

Source: Internet
Author: User
Tags button type


Let's take a look at the effect chart:




Shopping Cart



One, code



If you're interested in knowing how to do this, keep looking down. Words not much, directly on the code.



HTML code:


<! DOCTYPE html>
<html lang = "en" ng-app = "cart">
<head>
 <meta charset = "UTF-8">
 <title> Shopping cart </ title>
 <link rel = "stylesheet" href = "../ scripts / angular-1.4.0-rc.2 / docs / components / bootstrap-3.1.1 / css / bootstrap.min.css">
 <link rel = "stylesheet" href = "main.css">
</ head>
<body ng-controller = "cartCtr">
<table class = "table table-hover" ng-show = "items.length">
 <caption> AngularJS implements shopping cart </ caption>
 <tr>
 <th> Serial number </ th>
 <th> Product information </ th>
 <th> Unit price (yuan) </ th>
 <th> Quantity </ th>
 <th> Amount (yuan) </ th>
 <th> Action </ th>
 </ tr>
 <tr ng-repeat = "item in items">
 <td> {{$ index + 1}} </ td>
 <td> <a href="{{item.linkUrl}}" target="_blank" title="This link will take you to a Taobao-related page..."> {{item.title}} </a> < / td>
 <td class = "bold"> {{item.price | number: 2}} </ td>
 <td>
  <button type = "button" class = "btn btn-default btn-xs" ng-click = "reduce (item.id)" ng-disabled = "item.quantity <= 1">-</ button>
  <input type = "text" size = "5" ng-model = "item.quantity" ng-keydown = "quantityKeydown ()" ng-keyup = "quantityKeyup ()">
  <button type = "button" class = "btn btn-default btn-xs" ng-click = "add (item.id)"> + </ button>
 </ td>
 <td class = "bold mark"> {{item.price * item.quantity | number: 2}} </ td>
 <td>
  <button type = "button" class = "btn btn-default btn-xs" ng-click = "delete (item.id)"> Delete </ button>
 </ td>
 </ tr>
</ table>
<div class = "empty" ng-show = "! items.length"> The shopping cart is empty, go find the baby </ div>
<div class = "total">
 Selected: <span> {{getQuantites ()}} </ span>
 total:
 <span class = "mark" ng-show = "getTotalAmount () <15000"> {{getTotalAmount () | number: 2}} </ span>
 <span class = "mark" ng-show = "getTotalAmount ()> = 15000">
 {{getTotalAmount () * discount | number: 2}} <span class = "btn btn-xs"> (10%) </ span>
 <span class = "discount"> ({{getTotalAmount () | number: 2}}) </ span>
 </ span>
 <button type = "button" class = "btn btn-primary btn-sm" ng-click = "alertSubmit ()"> Settlement </ button>
</ div>
<script src = "../ scripts / angular-1.4.0-rc.2 / angular.js"> </ script> <script src = "app.js"> </ script>
</ body>
</ html> 


JS code:


/Created by wqq on 2016/5/25.
/var cartmodule = angular.module (' cart ', []);
 Cartmodule.controller (' cartctr ', [' $scope ', function ($scope) {$scope. Discount = 0.9; $scope. Items = [{id:10001,title: "The self-accomplishment of the web's entire stack of engineers", Price:40.80,quantity:2,linkurl: "https://detail.tmall.com/ item.htm?spm=a1z0d.6639537.1997196601.4.cwywjs&id=532166746631 "}, {id:10002,title:" MacBook Pro Retina 15 inches ", PR Ice:16088.00,quantity:1,linkurl: "https://detail.tmall.com/item.htm?spm=a1z0d.6639537.1997196601.26.cwywjs& id=45771116847 "}, {id:10003,title:" Surface book I5 128G single Display ", price:11088.00, Quantity:1,linkurl:" https://detail.t mall.com/item.htm?spm=a1z0d.6639537.1997196601.15.cwywjs&id=525614504276 "}, {id:10004, title:" Lenovo Yoga3Pro I5 4G ", price:7299.00, Quantity:1,linkurl:" https://detail.tmall.com/item.htm?spm=
 a1z0d.6639537.1997196601.37.cwywjs&id=41541519814 "}];
    $scope. Add = function (ID) {Angular.foreach ($scope. Items, function (item, index, array) {    if (item.id = = id) {item.quantity++}})
 }; $scope. reduce = function (ID) {Angular.foreach ($scope. Items, function (item, index, array) {if (item.id = = ID
 ) {item.quantity--;}})
 };
  The input box adds a KeyDown event to avoid entering a non positive integer $scope. Quantitykeydown = function (event) {event = event | | window.event; var target=event.target| |
  Event.srcelement;
  var keycode = Event.keycode; if ((Notoginseng <= keycode && keycode <= 40) | | (<= keycode && keycode <= 57) | | (<= keycode && keycode <= 105) | |
   KeyCode = = 8) {//directional key ↑→↓←, numeric key, backspace} else {console.log (keycode);
   Event.preventdefault ();
  return false;
}
 };
  KeyUp event, when the input number is 0 o'clock, refresh the text box contents $scope. Quantitykeyup = function (event) {event = event | | window.event; var target=event.target| |
  Event.srcelement;
  var keycode = Event.keycode;
 if (= = = KeyCode | | = = = keycode) {target.value=parseint (target.value);
 }}; Delete the item $scope. Delete = function (id) {$scope. items.forEach (function (item, index) {if (item.id = = ID) {If confirm ("OK) to remove this item from the shopping cart?"
    ") {$scope. Items.splice (index, 1);
   Return
 }
  }
 })
 };
 Calculates the number of selected items $scope. getquantites = function () {var quantities = 0; Angular.foreach ($scope. Items, function (item, index, array) {if (item.quantity) {quantities + = parseint (item.quanti
  TY);
 }
 });
 return quantities;
 };
 Calculates the total amount $scope. Gettotalamount = function () {var totalamount = 0;  Angular.foreach ($scope. Items, function (item, index, array) {TotalAmount + = item.quantity * Item.price;
 });
 return totalamount;
 }; $scope. Alertsubmit = function () {alert ("angular implements the shopping cart");}];


Second, analysis



Please ignore the bootstrap style, we only focus on angular, the code is very simple, let us briefly analyze:



1. Prepare



First we defined acartmodule, acartCtrcontroller, and introduced them into the HTML code, and we also defined an array in JSitemsto simulate things in the shopping cart.



2. Ng-repeat iterator



Toitemsload the dynamic traversal of the data, we use the built-in instructions in angular,ng-repeatwhich makes it easy to traverse the array, generate theDOMelements, and loop around 4<tr>tags:


<TR ng-repeat= "Item in Items" >


itemis anitemsarray of an object, is not the feeling that this is JS in thefor/inloop ~ ~ If you are a. NET developer, razor with asp.net mvc is familiar with the seamless operation of this other languageDOM, as for Java, Whether PHP has a similar syntax I don't know, I am a bitter. NET development.




Ng-repeat iterator



We can see that the first TD$indexis used, this isng-repeatinside, not what we defined, its value is currentlyiteminitemsthe index, starting from 0, so we use$index+1as a serial number, the other is (similaritem.linkUrl) Data binding.



We use {{Xxx|number:2}} in the unit price and amount Two column, this is a filter in angular, the function is to keep the previous value xxx two decimal, the amount, we certainly want to be accurate some. Just said that this is a filter, there are other, for examplecurrency, you can add a $ symbol in front of XXX to represent the United States dollar, you can own other filters use Baidu.



3. Adding events



The current interface has a number of +,-button, delete button, these events are relatively simple, the use of theng-clickelement to add click events. By passing the ID of a product, find the product, add, subtract and delete the item, but add a label to the "-" button, and byng-disabledname we can easily think of the HTMLdisabledattribute, and its function is whenng-disabledthe value is TrueDOMelement is disabled, the same is true for the following, and isng-showhidden when false. If the number is automatically converted to abooleanvalue, 0 is false, not 0 is true, note negative is also true!. Here I let when the number of 1 o'clock can not be reduced, because less will be directly deleted AH ~



Then add the event in the INPUT elementng-keydownso that it can only enter the direction key ↑→↓←, number keys,backspace. And then I tried it, and I did get it, but I could type a number like "00021", which is obviously not satisfying. I looked at Taobao's shopping cart and found that when you enter 0 o'clock, the contents of this text box will automatically refresh, remove the previous 0, so I added theng-keyupevent:


$scope. Quantitykeyup = function (event) {
  event = Event | | | window.event//compatible IE8 below, target is also
  var target= event.target| | event.srcelement;
  var keycode = Event.keycode;
  if (= = = KeyCode | | = = = = KeyCode) {
   target.value=parseint (target.value);
 };


When I enter 0 o'clock, the text box value will automatically refresh, why not add it to thekeydowninside and to add another event? That is because the value of the triggerkeydowneventtarget.valueis still the original value, there is no key to include this input, andkeydownthen the value is the new value, at this time we then let the triggerkeyupevent can achieve the purpose, can take care of the effect of Taobao shopping cart, I think my experience is better than it, because as long as it is not in the final input number text box will always lose focus ...



4. Statistics



The statistic quantity is the direct binding method, traversing the array return value.



Total amount of this piece, I made a 15000 dozen 90 percent design.ng-showDisplays the total amount with discounted information using hidden.



Third, summary



JS used a number offorEachtraversal arrays, ECMAScript5 Zhongyuan method isarray.forEach(function(item,index,array){});



The angular is also encapsulated,angular.forEach(array,function(item,index,array){});



I used both methods in the code, and I didn't know that it was a good performance.



At this point, the shopping cart has been completed, using angular two-way binding, can quickly achieve the number, amount of linkage changes. Hope this article content for everyone to learn and use angular can help, if there are questions can be exchanged message.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.