How to properly use a checkbox to change $rootScope value in AngularJS
I am trying to create a multilingual section to an app, that allows the users to front to choose their language of preference when the app loads.
In doing so, I set the $rootScope.language
to their preferred language.
Since that occurs only once at the load of the app, I wanted to add a preferences section where they can alter their choice, as needed.
In my Ionic V1 framework, I had created this in my template for the users to choose their language:
<ion-list>
<ion-radio ng-model="lang" ng-value="'en_US'" ng-click="updateLanguage('en_US')">English</ion-radio>
<ion-radio ng-model="lang" ng-value="'es_MX'" ng-click="updateLanguage('es_MX')">Espanol</ion-radio>
<ion-radio ng-model="lang" ng-value="'fr_CA'" ng-click="updateLanguage('fr_CA')">Francais</ion-radio>
</ion-list>
Here is part of my app.js that sets the $rootScope
value for the language:
.run(function($rootScope) {
$rootScope.language = 'en_US';
})
Along with that, I was using this in my controllers.js:
.controller('PreferencesCtrl', function($scope, $rootScope, $state, $ionicPlatform, $ionicLoading) {
alert('PreferencesCtrl');
$scope.lang = $rootScope.language;
//Update Language
$scope.updateLanguage = function(lang) {
$scope.lang = lang;
$rootScope.language = lang;
};
});
The issue I am running into is that I can successfully change the language once, but if I attempt to change it again, the whole page goes white, and nothing is being rendered. It also appears that by setting the $rootScope
, it also changes the view that is being rendered, as the back button goes away on the current screen.
My guess is that I am not setting the $rootScope.language
in the updateLanguage function as the information is not being logged to the console on the second attempt to change the language.
If I change the updateLangauge to this:
//Update Language
$scope.updateLanguage = function(lang) {
$scope.language = lang;
};
Then I don't experience any of the white screen issues, however, the language is only changed for that particular view - not across the entire app.
Any thoughts on where I may be approaching this incorrectly?
UPDATE: It appears that after the $rootScope is being set again in the updateLangauge function that my PreferencesCtrl is then not being executed. I added an alert to the controller to see if it was firing after the $rootScope was set for the second time (when the screen goes white) and the alert never fires. So, it's like the controller is gone after you update the $rootScope.