0

In my app the user sets his/her gender in the first view, and I store it in the localStorage.

$scope.setGender = function(gender){
    $scope.data.gender = gender;
    localStorage.setItem('paramGender', $scope.data.gender);
}

Then, the user goes to the second view and read its gender in the code by reading the localStorage:

$scope.data.gender = localStorage.getItem("paramGender"));

But if the the user goes back to the first view, change his/her gender and goes back to the second view, $scope.data.gender is not updated in the second controller.

How can I achieve that without reloading the whole second view? (I need to keep the cache because this second view is heavy).

halfer
  • 19,824
  • 17
  • 99
  • 186
Louis
  • 2,548
  • 10
  • 63
  • 120
  • Why not just update local storage to reflect the gender change? You can update single items there. – Daniel B Jan 09 '17 at 11:19
  • Yes this is what I do, I run `$scope.setGender` afterleaving the first view, but the controller js of the second view is not re-executed because it's in the cache – Louis Jan 09 '17 at 11:23
  • What do you mean controller in the cache? – digit Jan 09 '17 at 11:33
  • I mean that the controller of the second view is not re-executed unless the cache of the view is set to false: http://stackoverflow.com/a/37484441/2217647 – Louis Jan 09 '17 at 11:36

1 Answers1

0

I would simply use events in this case and a service.

app.factory('GenderService', [function() {
    var self = this;  
    self.gender = null;

      return {
        setGender: function(gender) {
          self.gender = gender;
        },
        getGender: function(){
          return self.gender;
        }
    }  
}]);

$scope.setGender = function(gender){
  $scope.data.gender = gender;
  GenderService.setGender(gender);
  $rootScope.$broadcast('genderUpdated', gender);
}

then in your other controller:

    $scope.data.gender = GenderService.getGender();
    $scope.$on('genderUpdated', function(event, data){
        $scope.data.gender = data;
    })

Regards,

Louis
  • 2,548
  • 10
  • 63
  • 120
Arno_Geismar
  • 2,296
  • 1
  • 15
  • 29
  • Thanks, but it doesn't seem it will work the "first time" (when the second view is not loaded yet), will it ? – Louis Jan 09 '17 at 12:06
  • ok Thanks a lot, isn't that just enough to simply put the variable on the rootscope ? – Louis Jan 09 '17 at 18:00
  • Yes it would be but I have a great disliking for putting variables on scopes they don't belong. Its not the rootscopes responsibility to know about genders. This method of doing things can easily get out of hand and be mis used. Generally I only put stuff on the rootscope that has to be known aoplication wide, for instance prefered locale. – Arno_Geismar Jan 09 '17 at 21:52