$watch 观察模型变化
$watch(watchFn,watchAction,deepWatch)
watchFn: Angular表达式字符串或是返回监控模型当前值的函数。
watchAction: 为一个函数或表达式,当watchFn变化时将调用,函数签名function(newValue,oldValue,scope)
deepWatch:为布尔值,设置为true将检查被监视对象的每个属性的每次变化。
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>shoppingCart</title>
<script src="http://lib.sinaapp.com/js/angular.js/angular-1.2.19/angular.min.js"></script>
<script>
function CartController($scope){
$scope.bill={};
$scope.items=[
{title:'book',quantity:8,price:5},
{title:'beer',quantity:12,price:9},
{title:'water',quantity:45,price:3}
];
$scope.totalCart=function(){
var total=0;
for(var i= 0,len=$scope.items.length;i<len;i++){
total+=$scope.items[i].price*$scope.items[i].quantity;
}
return total;
}
/*如果总值大于100则减去10元*/
$scope.subtotal=function(){
return $scope.totalCart()-$scope.bill.discount;
}
function calculateDiscount(newValue,oldvalue,scope){
$scope.bill.discount=newValue>100 ? 10 : 0;
}
/*当totalCount发生变化时,则重新计算折扣*/
$scope.$watch($scope.totalCart,calculateDiscount);
}
</script>
</head>
<body>
<div ng-controller="CartController">
<div ng-repeat="item in items">
<span>{{item.title}}</span>
<input ng-model="quantity">
<span>{{item.price|currency}}</span>
<span>{{item.price*item.quantity|currency}}</span>
</div>
<div>Total: {{totalCart()|currency}}</div>
<div>Discount:{{bill.discount|currency}}</div>
<div>Subtotal:{{subtotal()|currency}}</div>
</div>
</body>
</html>
改进版
$watch 监控字符串,当字符串所代表的数组发生变化时,则调用calculateTotals函数
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>shoppingCart2</title>
<script src="http://lib.sinaapp.com/js/angular.js/angular-1.2.19/angular.min.js"></script>
<script>
function CartController($scope){
$scope.bill={};
$scope.items=[
{title:'pink pig',quantity:8,price:3},
{title:'poly',quantity:5,price:6},
{title:'dark',quantity:9,price:2}
];
var calculateTotals=function(){
var total=0;
for(var i= 0,len=$scope.items.length;i<len;i++){
total+=$scope.items[i].price*$scope.items[i].quantity;
}
$scope.bill.totalCart=total;
$scope.bill.discount=total>100?10:0;
$scope.bill.subtotal=total-$scope.bill.discount;
};
/*当items数组中有元素发生变化时,就调用calculateTotal函数*/
$scope.$watch("items",calculateTotals,true);
}
</script>
</head>
<body ng-controller="CartController">
<div>Total:{{bill.totalCart|currency}}</div>
<div>Discount:{{bill.discount|currency}}</div>
<div>Subtotal:{{bill.subtotal|currency}}</div>
</body>
</html>
$watch 监视函数的变化
1.有一个对象,在作用域中有两个属性。发生变化时执行callMe()函数
$scope.$watch("things.a+things.b",callMe());
2.监视things上所有的属性
$scope.$watch("things",callMe(),true);
组织模块依赖
provider(name,Object OR constructor) : 一个可配置的有复杂逻辑的服务。
factory(name,$getFunction( )) : 一个不可配置的又复杂逻辑的服务。
service(name,constructor): 一个不可配置的简单逻辑的服务。
模块之间的依赖
var appMod=angular.module('app',['module1','module2']);