1

我正在使用 AngularJS,但遇到了一个问题,我似乎无法观察变量,这看起来很简单,但我不知道出了什么问题。

服务

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

设置控制器

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

正在观看的控制器

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

路径模式服务的包含工作正常,因为我可以强制阅读它,但除了应用程序首次运行(奇怪)之外,观察它什么都不做。

小提琴:http: //jsfiddle.net/7QbCG/10/

4

1 回答 1

2

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

于 2013-05-01T04:53:18.047 回答