I read the following questions and answers: Share data between AngularJS controllers, Update scope value when service data is changed, and Angular: Update service and share data between controllers.
My question is about the answers provided. The answers often suggest to $watch
and I don't understand why.
I wanted to share some values between controllers so I simply did this (this is a simplification of the code):
angular.module('app', [])
.factory('SomeSharedData', function()
{
return { 'pointer' : { 'someKey' : 'someValue' }};
})
.controller('Controller1', ['$scope', 'SomeSharedData', function($scope, SomeSharedData) {
$scope.pointer = SomeSharedData.pointer;
}])
.controller('Controller2', ['$scope', 'SomeSharedData', function($scope, SomeSharedData)
{
$scope.pointer = SomeSharedData.pointer;
}]);
Is this inheritly evil for some reason?
Why use something like:
$scope.$watch(function () { return SomeSharedData.someKey(); }, function (newValue) {
if (newValue) $scope.someKey = newValue;
});
It actually depends, in your case the pointer variable in the controller will be set to the SomeSharedData factory pointer variable. So there is no need to use $watch in your case as the variable will be set once.
But, what if you want to do something if the pointer variable in the controller changes. You will not know, whether the pointer variable has changed if you don't use $watch (that is what the $watch is for).
Like, take an example. Here i have created a model called pointer and i am watching for changes, and if anything changes the count is increased by 1 everytime. In this case the $watch is necessary. So, if in any case you want to do something if the model is changes, you can use $watch.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular $watch</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" ng-model="pointer">
{{pointer}}
<br>
<h3>Will increase if input changes:<h1>{{count}}</h1></h3>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
main.js
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', function ($scope) {
$scope.count = 1;
$scope.$watch('pointer', function(newValue, oldValue) {
if ( newValue !== oldValue ) {
$scope.count += 1;
}
});
}]);