服务中的angularjs数据不能在不同的控制器之间共享

时间:2015-06-26 02:44:54

标签: angularjs service

我创建服务:

.factory('patientListBarService', function() {
    var data = {
        pages: 0,
        total:0
    };
    return data;
})

我的ctl 1:

.controller('patientCtl', ['$scope', '$http', 'patientListBarService', function($scope, $http, patientListBarService){
    console.log(patientListBarService);
    $scope.pages = patientListBarService.pages;
    $scope.total = patientListBarService.total;
    $scope.$watch('patientListBarService.pages', function(newVal, oldVal, scope) {
        console.log('====pages:' + patientListBarService.pages);
        $scope.pages = patientListBarService.pages;
    });
    $scope.$watch('patientListBarService.total', function(newVal, oldVal, scope) {
        console.log('====total:' + patientListBarService.total);
        $scope.total = patientListBarService.total;
    });
}]);

my ctl 2:

controller('patientListCtl', ['$scope', 'patients', '$http', 'patientListBarService', function($scope, patients, $http, patientListBarService){
    console.log("----patient list ctl----");
    console.log(patients);
    patientListBarService.pages = patients.config.pages;
    patientListBarService.total = patients.config.total;
}]);

ctl1在ctl2之前运行。 在ctl2运行之后,ctl1' s

$scope.pages
$scope.total

在我的视图中显示正确的值。

然而,在我多次运行ctl2之后,它们的显示没有改变。

我是新手......

有人帮助我吗?谢谢!!!

1 个答案:

答案 0 :(得分:0)

如果将服务数据包装到对象中,则不需要监视,并且值将自动同步

.controller("Test1", function($scope, Serv){
  $scope.serv = Serv.data;

  $scope.modify = function(){
    $scope.serv.param1 = Math.random()*100;
    $scope.serv.param2 = Math.random()*100;
  }
})

.controller("Test2", function($scope, Serv){
  $scope.serv = Serv.data;
})

.factory("Serv", function(){
  var data = {
    param1: '',
    param2: ''
  }

  return {
    data: data
  }
});

jsbin