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;
});