環境
angularjs1.3
値の変更監視
ある値の変更を監視して、変更したら、◯◯するというときに便利な$scope.$watch と $scope.$warchGroup
について
1.単一の値を変更監視するとき=> $scope.$watch
を使用
以下はサンプル。
$scope.messageの変更を監視して、変更があればngと表示する。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="WatchController">
{{result}}<br>
{{message}}<br>
<input type="button" ng-click="change()" value="change">
</div>
<script type="text/javascript">
angular.module('app', [])
.controller('WatchController', ['$scope', function($scope) {
$scope.message = 'Hello World!';
$scope.result = '';
$scope.change = function() {
$scope.message = 'change!!';
};
$scope.$watch('message', function(newValue, oldValue, scope) {
if(angular.equals(newValue, oldValue)) {
scope.result = 'ok';
} else {
scope.result = 'ng';
}
});
}]);
</script>
</body>
</html>
2.複数の値の変化をまとめて監視する場合=>$scope.$watchGroup
を使用
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="WatchGroupController">
{{result}}<br>
<input type="button" ng-click="change1()" value="change1">
<input type="button" ng-click="change2()" value="change2">
<input type="button" ng-click="change3()" value="change3">
</div>
<script type="text/javascript">
angular.module('app', [])
.controller('WatchGroupController', ['$scope', function($scope) {
$scope.greeting = 'Hello, World1';
$scope.message2 = 'Hello, World2';
$scope.message3 = 'Hello, World3';
$scope.change1 = function() {
$scope.greeting = 'change!!';
};
$scope.change2 = function() {
$scope.message2 = 'change!!';
};
$scope.change3 = function() {
$scope.message3 = 'change!!';
};
$scope.result = '';
$scope.$watchGroup([
function() {
return $scope.greeting;
},
function() {
return $scope.message2;
},
function() {
return $scope.message3;
}
], function(newValue, oldValue, scope) {
scope.result = angular.toJson(newValue);
});
}]);
</script>
</body>
</html>