今天就写一个案列,让大家更加清楚地了解和掌握angularjs.也是基于有一定基础的人更好的快速学习。案例就是,简单的商城的购物车功能。通过angularJS可以对数据进行实时的读取和运算。
步骤如下:
1、在HTML中引进bootstrap样式和Angular库。
2、在script中定义模块和控制器。
3、在HTML中进行数据和控制器的绑定 。
代码如下:
1、
<html ng-app="shop"> 引入angular的入口 | ||
<head> | ||
<meta charset="UTF-8"> | ||
<title></title> | ||
</head> | ||
<link rel="stylesheet" type="text/css" href="js/bootstrap.min.css"/> | ||
<script type="text/javascript" src="js/angular.min.js"></script
|
2、
<script type="text/javascript"> | |
var app=angular.module("shop",[]); 定义angular的一个模块 | |
app.controller("shopcontrl",function($scope){ 定义控制器 | |
$scope.goodses=[ 定义一个数组的变量类似接口信息(模拟接口) | |
{goodsID:1,goodsName:"商品A",goodsPrice:100,count:1,subtotal:100}, | |
{goodsID:2,goodsName:"商品B",goodsPrice:156,count:1,subtotal:156}, | |
{goodsID:3,goodsName:"商品C",goodsPrice:15,count:1,subtotal:15}, | |
{goodsID:4,goodsName:"商品D",goodsPrice:22,count:1,subtotal:22}, | |
{goodsID:5,goodsName:"商品E",goodsPrice:666,count:1,subtotal:666}, | |
]; | |
$scope.totalQuantity=function(){ 定义一个函数方法计算总和 | |
var total=0; | |
for(var i=0;i<$scope.goodses.length;i++){ | |
total+=$scope.goodses[i].count*$scope.goodses[i].goodsPrice; | |
} | |
return total; | |
} | |
}) | |
</script> |
3、
<head> |
<body> | |
<div class="container" ng-controller="shopcontrl"> 在最外层的div中添加bootstrap的样式和 绑定控制器 | |
<div class="row"> bootstrap的样式 | |
<div class="col-md-8 col-md-offset-2"> bootstrap的样式 | |
<table class="table table-hover table-striped"> bootstrap的样式 | |
<tr> | |
<th>#</th> | |
<th>商品名称</th> | |
<th>商品单价</th> | |
<th>购买数量</th> | |
<th>小计金额</th> | |
<th>删除</th> | |
</tr> | |
<tr ng-repeat="goods in goodses"> <tr>中绑定循环语句 关键字 ng-repeat=" a in 数组对象" | |
<td>{{goods.goodsID}}</td> {{ }} 接收数据 或者用 ng-bind= "goods.goodsID"跟标签进行绑定 | |
<td>{{goods.goodsName}}</td> | |
<td>¥{{goods.goodsPrice}}</td> | |
<td><inputtype="text"ng-model="goods.count"></td> 用ng-model进行数据的双向绑定 | |
<td>¥{{goods.goodsPrice * goods.count}}</td> | |
<td> | |
<a href="#">删除</a> | |
</td> | |
</tr> | |
</table> | |
<div class="row"> | |
<div col-md-8 col-md-offset-2> | |
<div class="panel panel-default"> | |
<div class="panel-body text-right"> | |
总计金额:¥<span ng-bind="totalQuantity()"></span> 单向绑定调用函数 | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</body> |
经过以上的三步操作基本可以实现购物车的基本功能了。和大家共同努力,请持续关注。
<head> |