购物车代码示例
<!DOCTYPE html>
<html ng-app>
<head>
<base/>
<title>Your Shopping Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>//加载脚本
</head>
<body ng-controller='CartController'>
<h1>Your Order</h1>
<div ng-repeat='item in items'>
<span>{{item.title}}</span>
<input ng-model='item.quantity'/>
<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>
<button ng-click="remove($index)"> Remove </button>
</div>
<script>
function CartController($scope) {
////@formatter:off
$scope.items = [{
title : 'Paint pots',
quantity : 8,
price : 3.95
}, {
title : 'Polka dots',
quantity : 17,
price : 12.95
}, {
title : 'Pebbles',
quantity : 5,
price : 6.95
}];
////@formatter:on
$scope.remove = function(index) {
$scope.items.splice(index, 1);
};
}
</script>
</body>
</html>
①ng-app:ng-app属性告诉Angular 它应该管理页面的哪一部分。由于我们把它放在html元素上,
告知 Angular管理整个页面。 这个常常是你想要的, 但是如果你正在集成Angular和一个已存在的使用其他方式管理页面的应用,那么你可能需要放在应用的 div 上。
②ng-controller = 'controller':在Angular中,用
JavaScript 类管理的页面区域叫做控制器。 通过在body
标签中包含一
个控制器, 声明的 CartController 将管理body标签之间的任何东西。
③ng-repeat = 'item initems':ng-repeat代表为items
数组中每个元素拷贝一次这div
中的 DOM。 在div每次拷贝中,
同时设置了一个叫 item 的属性代表当前的元素, 所以我们能够在模板中使用。 正如你看到
的, 每个 div 中都包含了产品名称,数量,单价,总价和一个移除按钮。
④{{item.title}}:数据绑定是通过{{ }}把变量的值插入到页面某部分和保持同步。 完整的表达式{{item.title}}检索迭代中的当前项,然后将当前项的titile属性值插入到 DOM 中。
⑤ng-model = 'item.quantity':ng-model定义创建了输入字段和item.quantity之间的数据绑定。
span标签中的{{ }}建立了一个单向联系,在这里插入值。 但是应用程序需要知道当用户改变数量时, 能够改变总价,这是我们想要的效果。通过使用ng-model我们将与我们的模型保持同步更改。ng-model申明将
item.quantity的值插入到输入框中,无论何时用户输入一个新值将自动更新item.quantity。
⑥{{item.price | currency}}
{{itemprice * item.quantity | currency}}:我们希望单价和总价格式化成美元形式。Angular带有一个叫过滤器的特性,能够让我们转换文本,有一个叫currency的过滤器将为我们做这个美元形式格式化。
⑦<button ng-click = "remove($index)"> Remove</button>:这个允许用户点击产品旁边的Remove按钮从购物车中移除该项。我们已经建立了联系,以便点击这个按钮就可以调用remove()函数。
同时传递了$index, 这个包含了ng-repeat的
迭代顺序,以便知道要移除哪一项。
⑧function Carcontroller($scope){}:CartController管理这购物车的逻辑。通过这个我们告知Angular控制器
需要一个叫$scope 的对象。
$scope 就是用来把数据绑定到界面上的元素的。
⑨$scope.items=[{
quantity :8,
price :3.95
}, {
title :'Polka dots',
quantity :17,
price :12.95
}, {
title : 'Pebbles',
quantity :5,
price : 6.95
}];
通过定义$scope.items,我们已经创建一个虚拟数据代表了用户购物车中物品集合。 我们希望让这些数据能和界面绑定,因此我们把他们增加到$scope中。当然,这样的购物车是不能仅工作在内存中,也需要通知服务器端持久化数据。
⑩$scope.remove = function(index){
$scope.items.splice(index,1);
}
我们希望remove()函数能够绑定到界面上,因此我们也把它增加到$scope中。 对于这个内存中的购物车版本,remove()函数只是从数组中删除了它们。 因为通过ng-repeat创建的这些<div>是数据捆绑的, 当某项消失时,列表自动收缩。 记住, 无论何时用户点击移除按钮中的一个,都将从界面上调用remove()函数。