服务中的angularjs数据不能在不同的控制器之间共享
我创建服务:服务中的angularjs数据不能在不同的控制器之间共享,angularjs,service,Angularjs,Service,我创建服务: .factory('patientListBarService', function() { var data = { pages: 0, total:0 }; return data; }) 我的ctl 1: .controller('patientCtl', ['$scope', '$http', 'patientListBarService', function($scope, $http, patientListBa
.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;
});
}]);
我的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
$scope.pages
$scope.total
在我的视图上显示正确的值
但是,在我再次运行ctl2之后,它们的显示不会改变
我是新来的
有人帮我吗?谢谢 如果将服务数据包装到对象中,则不需要手表,值将自动同步
.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
}
});
这是不是·patientListBarService.pages=patients.config.pages;·'patientListBarService.total=patients.config.total;'每次都变吗?否则显示器不会改变是的,每次都会改变。。。