栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

Angular实现购物车计算示例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Angular实现购物车计算示例代码

使用AngularJS实现一个简单的购物车,主要感受强大的双向绑定和只关注对象不关注界面特性。

先看看界面:

点击+-操作和删除:

这些全部只需要操作数据源就行,不需要关注界面。

实现过程:

一、使用任何语言创建一个服务端:

  public class ShoppingCar
  {
    public string Title { get; set; }
    public decimal UnitPrice { get; set; }
    public int Count { get; set; }
  }
public ActionResult GetCar()
    {
      List cars = new List
      {
 new ShoppingCar { Title="苹果",Count=1,UnitPrice=2.5m},
 new ShoppingCar { Title="香蕉",Count=3,UnitPrice=1.5m},
 new ShoppingCar { Title="苦瓜",Count=1,UnitPrice=3.5m},
 new ShoppingCar { Title="黄瓜",Count=3,UnitPrice=2.2m}
      };
      return Json(cars,JsonRequestBehavior.AllowGet);
    }

    public ActionResult AddCar(List car)
    {
      return Json("ok", JsonRequestBehavior.AllowGet);
    }

二、前台实现:

  
    
标题 单价 数量 小计 删除
{{item.Title}} {{item.UnitPrice}} {{item.Count*item.UnitPrice | number:2}}

总价格:{{ total | number:2}}

三、Angular部分
 

 var app = angular.module('DemoApp', []);

  app.controller('CartController', ['$scope', '$http', function ($scope, $http) {
    $scope.ShoppingCar = {}
    var GetCar = function () {
      $http.get('/Employee/GetCar')
      .success(function (response) {
 $scope.ShoppingCar = response;
 GetTotal();
      });
    }
    $scope.total = 0;
    var GetTotal = function () {
      for (var i = 0; i < $scope.ShoppingCar.length; i++) {
 var item = $scope.ShoppingCar[i];
 $scope.total += item.Count * item.UnitPrice;
      }
    }

    $scope.UpdateCar = function (title, count) {
      for (var i = 0; i < $scope.ShoppingCar.length; i++) {
 var item = $scope.ShoppingCar[i];
 if (item.Title == title) {
   item.Count = item.Count + count;//这里可以增加上下限制
   if (item.Count < 0) {
     $scope.ShoppingCar.splice(i, 1);
   }
 }
      }
      GetTotal();
    }
    $scope.submit = function () {
      $http.post('/Employee/AddCar', $scope.ShoppingCar)
   .success(function (response) {
   alert(response);
      });
    }
    GetCar();
  }]);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/89806.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号