angular的$watch 函数



它的函数签名为$watch(watchFn, watchAction, deepWatch)


其中每个参数的详细含义如下。
watchFn

该参数是一个带有Angular表达式或者函数的字符串,它会返回被监控的数据模型的当前值。这个表达式将会被执行很多次,所以你要保证它不会产生其他副作用。也就是说,要保证它可以被调用很多次而不会改变状态。基于同样的原因,监控表达式应该很容易被计算出来。如果你使用字符串传递了一个Angular表达式,那么它将会针对调用它的那个作用域中的对象而执行。
watchAction

这是一个函数或者表达式,当watchFn 发生变化时会被调用。如果是函数的形式,它将会接收到watchFn的新旧两个值,以及作用域对象的引用。其函数签名为function(newValue, oldValue, scope)。


我们再回到第1章的购物车案例,把它的功能扩充完整。例如,当用户添加到购物车中的商品价值超过100美元的时候,我们会给他10美元的折扣。我们将会使用下面这种模板:
<div ng-controller="CartController">
  <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>
  </div>
  <div>Total: {{totalCart() | currency}}</div>
  <div>Discount: {{bill.discount | currency}}</div>
  <div>Subtotal: {{subtotal() | currency}}</div>
</div>

而CartController看起来可能像下面这样:
function CartController($scope) {
  $scope.bill = {};
  $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}
  ];
  $scope.totalCart = function() {
    var total = 0;
    for (var i = 0, len = $scope.items.length; i < len; i++) {
      total = total + $scope.items[i].price * $scope.items[i].quantity;
    }
    return total;
  }
  $scope.subtotal = function() {
    return $scope.totalCart() - $scope.discount;
  };
  function calculateDiscount(newValue, oldValue, scope) {
    $scope.bill.discount = newValue > 100 ? 10 : 0;
  }
  $scope.$watch($scope.totalCart, calculateDiscount);
}

注意CartController 的底部,我们在totalCart() 的值上面设置了一个监控,用来计算此次购物的总价。只要这个值发生变化,监控器就会调用calculateDiscount() , 然后我们就可以把折扣设置为相应的值。如果总价超过100美元,我们将会把折扣设置为10美元。否则,折扣为0。

图2-1展示了用户将会看到的效果。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值