Watch a service variable from a controller

Watching a service variable inside a controller is little different than watching a controller variable.
I will demonstrate the same here in this post.

I will create a module










var app=angular.module('app',[]);

Next I will attach a service to the above module.
app.service('myService', function () {
this.myVar = 10;
this.changeMyVar = function (val) {
    this.myVar = val;
};
});

In my service I declared a variable and created function to set its value.

Next I will attach a controller to the same module.

app.controller('myController', function ($scope, myService) {
myService.myVar = 200;  //changing value to trigger $watch
//watch block
$scope.$watch(function () {
return myService.myVar;
}, function (newVal) {
console.log(newVal);
});
)};

To sum up everything

app = angular.module('app', []);
//controller
app.controller('myController', function ($scope, myService) {
myService.myVar = 200;//changing value to trigger $watch
//watch block
$scope.$watch(function () {
return myService.myVar;
}, function (newVal) {
console.log(newVal);
});
});

//service
app.service('myService', function () {
this.myVar = 10;
this.changeMyVar = function (val) {
this.myVar = val;
};
});


That's all we need to do to catch service property changes from a controller. Now we will be notified whenever there is any change in the value of myVar variable.

Comments

Popular Posts