David Nguyen
David Nguyen

Reputation: 8528

simple $watch on service doesn't work but can access service

I'm picking up AngularJS and I'm running into an issue where I cannot seem to watch a variable, seems pretty straight forward but I can't figure out what is wrong.

Service

app.factory('pathModalService', function() {
var path;
return {
    getPath: function(){
        console.log('get path');
        return path;
    },
    setPath: function(newPath){
        console.log('set path:' + newPath);
            path = newPath;
    }
}
});

Controller that sets

app.controller('PathsCtrl', ['$scope', 'pathModalService', function($scope, pathModalService){
$scope.edit_path = function(){
    pathModalService.setPath('test1');
}
}]);

Controller that is watching

app.controller('PathModalCtrl', ['$rootScope', 'pathModalService', function($scope, pathModalService){
$scope.$watch(pathModalService.path, function() {
    console.log('Change to Path');
}, true);
$scope.test = function(){
    console.log(pathModalService.getPath());
}
}]);

The inclusion of the path modal service is working correctly as I can forcefully read it, but watching it does nothing except when the app first runs (weird).

Fiddle: http://jsfiddle.net/7QbCG/10/

Upvotes: 1

Views: 402

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

pathModalService.path is undefined since path is a closure variable. You need to register the watch on pathModalService.getPath

$scope.$watch(pathModalService.getPath, function() {
    console.log('Change to Path');
}, true);

Demo: Fiddle

My Test o/p for fiddle enter image description here

Upvotes: 2

Related Questions