2

I have a controller I'm using for 3 different views that collects data. I'm watching 2 scopes in it. This is an excerpt:

  // predefine place before Google Maps API GET
  $scope.place = {
    formatted_address: '',
    url: ''
  };

  // watch place in case of change (doesn't work otherwise)
  $scope.$watch('place', function () {
    $scope.poll.Poll.Location    = $scope.place.formatted_address;
    $scope.poll.Poll.UrlLocation = $scope.place.url;
  });

Everything works fine on view 1, the $scope.poll.Poll.Location and the $scope.poll.Poll.Location gets filled with data of the Google Maps api.

But when I click on a button which changes my route (ui-sref="view2"), which is using the same controller, the scopes are empty.

How can I transfer the watched scopes between multiple views with the same controller?

herrh
  • 1,328
  • 1
  • 16
  • 33

2 Answers2

2

If you have multiple states using the same controller, then both states get it's own instance of the controller. You have to pass the data as a param to the second state.

Like this:ui-sref="view2({poll: poll})"

Don't forget to add the param to the state definition in $stateProvider.

$stateProvider.state("homepageState", {
    url: "/home/",
    templateUrl: "templates/homePage.html",
    controller: "HomePageController",
    params: {
       poll: null //initial
    }
});

In your controller you can get the value by calling $stateParams.poll

You also could make use of angular services. A service is instantiated only once and is reusable.

If you have to wait for data from an unknown source, then you have to take a look at Promise.when()

when(value, [successCallback], [errorCallback], [progressCallback]);

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

com2ghz
  • 2,706
  • 3
  • 16
  • 27
-1

Put then on $rootScope may works

$scope.$watch('place', function () {
  $rootScope.poll.Poll.Location    = $scope.place.formatted_address;
  $rootScope.poll.Poll.UrlLocation = $scope.place.url;
});
Thiago Frias
  • 134
  • 1
  • 9
  • I don't think the rootScope is a proper way to handle this – com2ghz Jan 27 '16 at 19:11
  • if he changes the route all the current scope is lost, put then on rootScope will persist the data no matter which controller he is in – Thiago Frias Jan 27 '16 at 19:32
  • but to work you have to put all the `poll` object in the `$rootScope` otherwise you will get errors – Thiago Frias Jan 27 '16 at 19:34
  • You are creating a unnecessary watch in the rootScope that never will be cleaned up. The rootScope is meant to be used for global functionality. $watch is a dirty checking if some value has been modified and could couse performance problems. This would be the last option if you already tried the proper way. – com2ghz Jan 27 '16 at 19:39