AnjularJs学习--part1

【一个例子:购物车】
让我们看一个稍微大一点的例子。此例中展示了Augular更多的特性。我们想象一下我们要干什么去创建我们购物app。在这个app的某些地方我们将显示用户的购物车并且让他编辑。让我们掠过中间的步骤。

 1 <html ng-app='myApp'>
 2 <head>
 3 <title>Your Shopping Cart</title>
 4 </head>
 5 <body ng-controller='CartController'>
 6 <h1>Your Order</h1>
 7 <div ng-repeat='item in items'>
 8 <span>{{item.title}}</span>
 9 <input ng-model='item.quantity'>
10 <span>{{item.price | currency}}</span>
11 <span>{{item.price * item.quantity | currency}}</span>
12 <button ng-click="remove($index)">Remove</button>
13 </div>
14 <script src="angular.js"></script>
15 <script>
16 function CartController($scope) {
17 $scope.items = [
18 {title: 'Paint pots', quantity: 8, price: 3.95},
19 {title: 'Polka dots', quantity: 17, price: 12.95},
20 {title: 'Pebbles', quantity: 5, price: 6.95}
21 ];
22 $scope.remove = function(index) {
23 $scope.items.splice(index, 1);
24 }
25 }
26 </script>
27 </body>
28 </html>

<html ng-app>:ng-app属性告诉Anjular要管理页面的那些部分。

<body ng-controller='CartController'>:在Angular中,你管理页面某一部分的javascript类叫做controller。

<div ng-repeat='item in items'>:ng-repeat属性告诉这里边的东西是要循环显示的。

<span>{{item.title}}</span>:通过{{}}来进行数据绑定,我们能从页面的其他部分插入数据,然后使他保持同步。

<input ng-model='item.quantity'>:ng-model做了文本域和属性之间的数据绑定。

{{}}是一种单向数据绑定。我们同步数据的改变通过使用ng-model。当用户填写了一个新值的时候,ng-model改变了item.quantity的值。

<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>:anjular提供了一种特性叫做过滤器,使我们能够格式化文本。有这么一些列过滤器叫做currency过滤器能格式化美元

<button ng-click='remove($index)'>Remove</button>:我们传入了一个$index参数,它代表了ng-repeat的序号,所以我们知道要删除的是谁。

function CartController($scope) {
这个CartController处理购物车的业务逻辑。我们告诉Anjular这个控制器需要$scope。$scope就是使我们能够绑定数据到UI中的东西
$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}
];
本例中加的这个items要在UI中显示。
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
我们想让remove()方法在UI可用,所以我们把它加入到了$scope变量里。

posted @ 2014-08-28 09:52  lvxin  阅读(150)  评论(0)    收藏  举报