0

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?

kenshinji
  • 2,021
  • 4
  • 25
  • 39
ju xiaomi
  • 53
  • 5
  • Duplicate: http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers – Jessedc Nov 19 '15 at 05:57
  • Check this question : http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers – Ankit Gupta Nov 19 '15 at 06:20
  • I don't really think your problem is with sharing data between controllers. Instead, I think your problem is with the fact that when you open a page in a new window, it is a new app, and it **cannot** communicate with the other app. You can only share data, services, events, etc. with controllers that are in the same app (i.e. same window). – Claies Nov 19 '15 at 06:25
  • @Claies yes, you understand correctly! – ju xiaomi Nov 19 '15 at 06:33
  • @Claies I use a _blank target not self, it doesn't work. But how to solve it. My question name make a mistake. – ju xiaomi Nov 19 '15 at 06:34
  • there isn't a solution, at least not in the way you are trying. If you target `_blank`, then you have to treat the app that loads in that new window as a separate app, and the only way to pass data to it would be by using query string parameters. – Claies Nov 19 '15 at 08:26
  • Angular is a Single Page Application, it is not a framework designed to manage more than one page in your browser simultaneously. – Claies Nov 19 '15 at 08:26

2 Answers2

0

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);
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

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")
Emre_
  • 31
  • 2
  • 6