AngularJs_watchDifference
$watch method Difference in AngularJs.
by Ryan Hsu
HTML
<div ng-app>
<div ng-controller='demoCtrl'>
<h1>比較$watch()與$watchCollection()的不同</h1>
<input type='button' value='屬性改變(深層)' ng-click='deepChange()'>
<input type='button' value='屬性改變(淺層)' ng-click='shallowChange()'>
<input type='button' value='重建物件' ng-click='rebuild()'>
<input type='button' value='清除' ng-click='clear()'>
<h2>$watch()</h2>
<li ng-repeat='log in watchLog'>{{log.log}}</li>
<h2>$watchCollection()</h2>
<li ng-repeat='log in watchCollectionLog'>{{log.log}}</li>
<h2>$watch(, true)</h2>
<li ng-repeat='log in watchtrueLog'>{{log.log}}</li>
</div>
</div>
JavaScript
function demoCtrl($scope) {
$scope.dest = [{
id: 1,
name: 'Peter'
}]
$scope.$watch('dest', function() {
$scope.watchLog.push({
log: '觸發!'
});
});
$scope.$watchCollection('dest', function() {
$scope.watchCollectionLog.push({
log: '觸發!'
});
});
$scope.$watch('dest', function() {
$scope.watchtrueLog.push({
log: '觸發!'
});
}, true);
$scope.deepChange = function() {
$scope.dest[0].id = $scope.dest[0].id + 1;
}
$scope.shallowChange = function() {
$scope.dest.push({
id: 1,
name: 'Peter'
});
}
$scope.rebuild = function() {
$scope.dest = [{
id: 1,
name: 'Peter'
}]
}
$scope.clear = function() {
$scope.watchLog = [];
$scope.watchCollectionLog = [];
$scope.watchtrueLog = [];
}
$scope.clear();
}