Angular实现简单购物车

1、AngularJS简介

AngularJS是一个前端MVVM框架。

angular的英文字面意思是:有角的; 用角测量的

AngularJS是协助搭建单页面工程(SPA)的开源前端框架。它通过MVC模式使得开发与测试变得更容易。

AngularJS试图成为WEB应用中的一种端对端的解决方案。它将指导开发整个应用。

AngularJS于2009年发布第一个版本,由Google进行维护,压缩版94k。

 

1.3版后不再支持IE8
1.3版后不支持全局控制器
2.0版 alpha

git仓库:https://github.com/angular/

官网:https://www.angularjs.org/

http://www.angularjs.cn/中文社区

http://www.apjs.net/ 中文网

2、AngularJS特点

1、功能强大,完善的前端MVVM框架,包含模板,数据双向绑定,路由,模块化,服务,过滤器,依赖注入等所有功能;
2、声明式风格、直观、易于操作、访问和实现
3、支持单元测试、本身基于TDD完成
4、致力于减轻开发人员在开发AJAX应用过程中的痛苦
5、angular 是最适合CRUD的SPA 单页面的应用程序

不适合SEO、交互频繁的,如游戏之类交互体验网站

AngularJS的核心组件:

3、实现简单购物车

3.1、本次用到AngularJS的相关指令

3.1.1、ng-app指令

  1、用于告诉 AngularJS 应用当前这个元素是根元素。

  2、所有 AngularJS 应用都必须要要一个根元素。

  3、HTML 文档中只允许有一个ng-app指令,如果有多个ng-app指令,则只有第一个会被使用。

语法:

<element ng-app="modulename">
...
 在 ng-app 根元素上的内容可以包含 AngularJS 代码
...
</element>

相关链接:http://www.runoob.com/angularjs/ng-ng-app.html

3.1.2、ng-controller指令

  1、用于为你的应用添加控制器。

  2、在控制器中,你可以编写代码,制作函数和变量,并使用 scope 对象来访问。

语法:

<element ng-controller="expression"></element>

示例:

<div ng-app="myApp" ng-controller="myCtrl">

Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>

相关链接:http://www.runoob.com/angularjs/ng-ng-controller.html

3.1.3、ng-repeat指令

  1、用于循环输出指定次数的 HTML 元素。

  2、集合必须是数组或对象

 语法:

<element ng-repeat="expression"></element>

示例:

<body ng-app="myApp" ng-controller="myCtrl">

<h1 ng-repeat="x in records">{{x}}</h1>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.records = [
        "示例1",
        "示例2",
        "示例3",
        "示例4",
    ]
});
</script>
</body>

 相关链接:http://www.runoob.com/angularjs/ng-ng-repeat.html

 3.1.4、ng-model指令

  1、绑定了 HTML 表单元素到 scope 变量中。

  2、如果 scope 中不存在变量, 将会创建它。

语法:

<element ng-model="name"></element>

 示例:

<div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="name">
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
</script>

 相关链接:http://www.runoob.com/angularjs/ng-ng-model.html

3.1.5、ng-click指令

  1、告诉了 AngularJS HTML 元素被点击后需要执行的操作。

语法:

<element ng-click="expression"></element>

示例:

<button ng-click="count = count + 1" ng-init="count=0">OK</button>

相关链接:http://www.runoob.com/angularjs/ng-ng-click.html 

3.1.6、ng-bind指令

  1、告诉 AngularJS 使用给定的变量或表达式的值来替换 HTML 元素的内容。

  2、如果给定的变量或表达式修改了,指定替换的 HTML 元素也会修改。

 语法:

<element ng-bind="expression"></element>
或作为 CSS 类:
<element class="ng-bind: expression"></element>

 示例:

<div ng-app="" ng-init="myText='Hello World!'">
  <p ng-bind="myText"></p>
</div>

 相关链接:http://www.runoob.com/angularjs/ng-ng-bind.html

 3.1.7、ng-init指令

  1、执行给定的表达式。

  2、添加一些不必要的逻辑到 scope 中,建议你可以在控制器中 ng-controller 指令执行它 

 语法:

<element ng-init="expression" ></element>

示例:

<div ng-app="" ng-init="myText='Hello World!'">
<h1>{{myText}}</h1>

相关链接:http://www.runoob.com/angularjs/ng-ng-init.html

3.2、示例

3.2.1、新建一个项目并引入angularJS,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular购物车</title>
</head>
<body>

<script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
</body>
</html>

 3.2.2、添加根元素和控制器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular购物车</title>
</head>
<body>
<!--定义了一个名为shop根元素和一个名为shopping的控制器-->
<div ng-app="shop" ng-controller="shopping">

</div>
<script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
<script type="text/javascript">
    var app=angular.module('shop',[]);
    //使用$scope 对象来调用控制器, $scope 是一个应用对象(属于应用变量和函数)
    //控制器的 $scope (相当于作用域、控制范围)用来保存AngularJS Model(模型)的对象
    app.controller('shopping',function ($scope) {

    })
</script>
</body>
</html>

应用解析:

  1、AngularJS 应用程序由 ng-app 定义。应用程序在 <div> 内运行。

  2、ng-controller="shopping" 属性是一个 AngularJS 指令。用于定义一个控制器。

  3、shopping函数是一个 JavaScript 函数。

  4、AngularJS 使用$scope 对象来调用控制器。

  5、在 AngularJS 中, $scope 是一个应用对象(属于应用变量和函数)。

  6、控制器的 $scope (相当于作用域、控制范围)用来保存AngularJS Model(模型)的对象。

3.2.3、添加默认数据

app.controller('shopping',function ($scope) {
        //往控制器里添加products属性
        $scope.products=[
            {shopsname:'小米Mix3',shopsnum:3,shopprice:3999.9},
            {shopsname:'华为20',shopsnum:5,shopprice:4999.9},
            {shopsname:'小米笔记本',shopsnum:6,shopprice:6999.9},
            {shopsname:'努比亚X',shopsnum:10,shopprice:3999.9},
            {shopsname:'手办',shopsnum:10,shopprice:9999.8}];
    })

3.2.3、数据渲染

<div ng-app="shop" ng-controller="shopping">
    <table border="1" cellspacing="0" cellpadding="0" width="100%">
        <caption style="font-size: 28px;">Angular</caption>
        <tr><th>序号</th><th>名称</th><th>单价</th><th>数量</th><th>小计</th><th>操作</th></tr>
        <tr ng-repeat="item in products">
            <td>{{$index+1}}</td>
            <td>{{item.shopsname}}</td>
            <td>{{item.shopprice}}</td>
            <td>{{item.shopsnum}}</td>
            <!--计算后保留后两位小数-->
            <td>{{(item.shopsnum*item.shopprice).toFixed(2)}}</td>
            <td><a href="#">删除</a></td>
        </tr>
    </table>
</div>

完成后效果如下:

提示:$index慎用  疑问请点击:点击查看$index中的坑

 3.2.4、添加增加数量和减少数量的按钮

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular购物车</title>
</head>
<body>
<!--定义了一个名为shop根元素和一个名为shopping的控制器-->
<div ng-app="shop" ng-controller="shopping">
    <table border="1" cellspacing="0" cellpadding="0" width="100%">
        <caption style="font-size: 28px;">Angular</caption>
        <tr><th>序号</th><th>名称</th><th>单价</th><th>数量</th><th>小计</th><th>操作</th></tr>
        <tr ng-repeat="item in products">
            <td>{{$index+1}}</td>
            <td>{{item.shopsname}}</td>
            <td>{{item.shopprice}}</td>
            <td>
                <!--增加两个按钮,调用控制器里的函数方法-->
                <button ng-click="reducesum($index)">-</button>
                <input type="text" ng-model="item.shopsnum">
                <button ng-click="addsum($index)">+</button>
            </td>
            <!--计算后保留后两位小数-->
            <td>{{(item.shopsnum*item.shopprice).toFixed(2)}}</td>
            <td><a href="#">删除</a></td>
        </tr>
    </table>
</div>
<script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
<script type="text/javascript">
    var app=angular.module('shop',[]);
    //使用$scope 对象来调用控制器, $scope 是一个应用对象(属于应用变量和函数)
    //控制器的 $scope (相当于作用域、控制范围)用来保存AngularJS Model(模型)的对象
    app.controller('shopping',function ($scope) {
        //往控制器里添加products属性
        $scope.products=[
            {shopsname:'小米Mix3',shopsnum:3,shopprice:3999.9},
            {shopsname:'华为20',shopsnum:5,shopprice:4999.9},
            {shopsname:'小米笔记本',shopsnum:6,shopprice:6999.9},
            {shopsname:'努比亚X',shopsnum:10,shopprice:3999.9},
            {shopsname:'手办',shopsnum:10,shopprice:9999.8}];
        //增加数量
        $scope.addsum=function (i) {
            return $scope.products[i].shopsnum++;
        };
        //减少数量
        $scope.reducesum=function (i) {
            //找到products里面对应的shopsnum进行判断
            if($scope.products[i].shopsnum>=2){
                return $scope.products[i].shopsnum--;
            }else{
                alert("已经最少了!");
            }
        };
    });
</script>
</body>
</html>

效果如下所示:

 

 3.2.5、计算合计

 table里面追加:

<tr>
   <td colspan="6" align="right" style="padding: 0px 50px;">合计:<span ng-bind="total()"></span></td>
</tr>

控制器里面追加:

//计算总数
 $scope.total=function(){
   var priceAll = 0;
   for(var i= 0;i<$scope.products.length;i++){
       priceAll+=$scope.products[i].shopprice*$scope.products[i].shopsnum;
   }
   return priceAll.toFixed(2);
 };

效果如下所示:

 3.2.5、删除一行数据

a标签添加点击事件:

 <td><a href="#" ng-click="remove($index)">删除</a></td>

控制器追加:

//删除
        $scope.remove=function(index){
            if(confirm('确定要删除吗?')){
                alert("删除成功!");
                $scope.products.splice(index,1);
            }
        };

 完成后效果如下:

 3.2.5、页面添加css美化

<style type="text/css">
        table{
            text-align: center;
        }
        tr{
            height: 40px;
            line-height: 40px;
        }
        tr:hover{
            background: #eeeeee;
        }
        input{
            background: transparent;
            width: 40px;
            height: 20px;
            line-height: 20px;
            padding: 0;
            border:none;
            outline:none;
            border-top: 1px solid gray;
            border-bottom: 1px solid gray;
            text-align: center;
        }
        button{
            width: 20px;
            height: 22px;
            border: 1px solid gray;
            border-left: none;
            cursor: pointer;
            outline:none;
            margin-left: -4px;
        }
        #reduce{
            border-right: none;
            border-left:1px solid gray;
            margin-right: -5px;
        }
        span{
            color: red;
            font-size: 22px;
        }
        a{
            text-decoration: none;
            column-rule: red;
        }
    </style>

完成效果如下: 

 3.2.5、完整示例

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular购物车</title>
    <style type="text/css">
        table{
            text-align: center;
        }
        tr{
            height: 40px;
            line-height: 40px;
        }
        tr:hover{
            background: #eeeeee;
        }
        input{
            background: transparent;
            width: 40px;
            height: 20px;
            line-height: 20px;
            padding: 0;
            border:none;
            outline:none;
            border-top: 1px solid gray;
            border-bottom: 1px solid gray;
            text-align: center;
        }
        button{
            width: 20px;
            height: 22px;
            border: 1px solid gray;
            border-left: none;
            cursor: pointer;
            outline:none;
            margin-left: -4px;
        }
        #reduce{
            border-right: none;
            border-left:1px solid gray;
            margin-right: -5px;
        }
        span{
            color: red;
            font-size: 22px;
        }
        a{
            text-decoration: none;
            column-rule: red;
        }
    </style>
</head>
<body>
<!--定义了一个名为shop根元素和一个名为shopping的控制器-->
<div ng-app="shop" ng-controller="shopping">
    <table border="1" cellspacing="0" cellpadding="0" width="100%">
        <caption style="font-size: 28px;">Angular</caption>
        <tr><th>序号</th><th>名称</th><th>单价</th><th>数量</th><th>小计</th><th>操作</th></tr>
        <tr ng-repeat="item in products">
            <td>{{$index+1}}</td>
            <td>{{item.shopsname}}</td>
            <td>{{item.shopprice}}</td>
            <td>
                <!--增加两个按钮,调用控制器里的函数方法-->
                <button ng-click="reducesum($index)" id="reduce">-</button>
                <input type="text" ng-model="item.shopsnum">
                <button ng-click="addsum($index)">+</button>
            </td>
            <!--计算后保留后两位小数-->
            <td>{{(item.shopsnum*item.shopprice).toFixed(2)}}</td>
            <td><a href="#" ng-click="remove($index)">删除</a></td>
        </tr>
        <tr>
            <td colspan="6" align="right" style="padding: 0px 50px;">合计:<span ng-bind="total()"></span></td>
        </tr>
    </table>
</div>
<script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
<script type="text/javascript">
    var app=angular.module('shop',[]);
    //使用$scope 对象来调用控制器, $scope 是一个应用对象(属于应用变量和函数)
    //控制器的 $scope (相当于作用域、控制范围)用来保存AngularJS Model(模型)的对象
    app.controller('shopping',function ($scope) {
        //往控制器里添加products属性
        $scope.products=[
            {shopsname:'小米Mix3',shopsnum:3,shopprice:3999.9},
            {shopsname:'华为20',shopsnum:5,shopprice:4999.9},
            {shopsname:'小米笔记本',shopsnum:6,shopprice:6999.9},
            {shopsname:'努比亚X',shopsnum:10,shopprice:3999.9},
            {shopsname:'手办',shopsnum:10,shopprice:9999.8}];
        //增加数量
        $scope.addsum=function (i) {
            return $scope.products[i].shopsnum++;
        };
        //减少数量
        $scope.reducesum=function (i) {
            //找到products里面对应的shopsnum进行判断
            if($scope.products[i].shopsnum>=2){
                return $scope.products[i].shopsnum--;
            }else{
                alert("已经最少了!");
            }
        };
        //计算总数
        $scope.total=function(){
            var priceAll = 0;
            for(var i= 0;i<$scope.products.length;i++){
                priceAll+=$scope.products[i].shopprice*$scope.products[i].shopsnum;
            }
            return priceAll.toFixed(2);
        };
        //删除
        $scope.remove=function(index){
            if(confirm('确定要删除吗?')){
                alert("删除成功!");
                $scope.products.splice(index,1);
            }
        };
    });
</script>
</body>
</html>
View Code

效果:

完成在下告辞,下期再见,拜拜!

原文地址:https://www.cnblogs.com/combat/p/10135367.html