yangbo5207 / everyday

Something I learn every day.
5 stars 0 forks source link

angularjs: $scope.$watch 在监听时因为this指向问题而出错 #25

Open yangbo5207 opened 8 years ago

yangbo5207 commented 8 years ago
$s.sum = function() {
    return this.iphone.price * this.iphone.number + this.iphone.fre;
}
$s.$watch($s.sum, function(newVal, oldVal) {
    console.log(newVal, oldVal);
})

在监听$s.sum时,因为内部函数使用了this, 而在$watch中,监听$s.sum会导致this指向改变,因此作如下修正,便没有什么问题了

$s.sum = function() {
    return $s.iphone.price * $s.iphone.number + $s.iphone.fre;
}
$s.$watch($s.sum, function(newVal, oldVal) {
    $s.iphone.fre = newVal > 500 ? 0 : 10;
})