I use service to share data cross controllers and it works. First page use a controller named ACtrl
:
<a ng-click='doit()'>click me</a>
Second page use a different controller BCtrl
:
<label>{{person.name}}</label>
In doit
function, I shared an object using service. In BCtrl I get the share object ,all is fine. But I want the second page open an another window, so I change first page as below:
<a ng-click='doit()' href='_blank'>click me</a>
Then second page doesn't work. So how to resolve this problem?
You can send data through events, like
ACtrl
data = {a: 1, b: 2}
$rootScope.$broadcast('dataChanged', data);
BCtrl
$scope.$on('dataChanged', function(e, data) {
console.log(data);
}
Firstly define a factory service in your service.js
.factory('DataScopeService', function($rootScope) {
var mem = {};
return {
set: function(key, value) {
mem[key] = value;
},
get: function(key) {
return mem[key];
}
};
})
Then, use this service to set and get data from any controller in your project.
ControllerA
DataScopeService.set("selectedTimePeriod", '1');
ControllerB
$scope.selectedTime = DataScopeService.get("selectedTimePeriod")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.