11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

angularjs値の変更監視

Last updated at Posted at 2015-08-08

環境

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>
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?