2
votes

I have this HTML

<button class="btn btn-info" ng-click="setLanguage('en')">English</button>
<button class="btn btn-info" ng-click="setLanguage('de')">Danish</button>
<p>{{name[language]}}</p>

and javascript

$scope.language='en';  //initial default value
$scope.setLanguage = function(language) {
    $scope.language = language;    
   }

i am binding language to button for 2 languages.based on the language selected, the content will be shown. how to store en or de to localstorage. if i refresh or change the page also, the set language should be same. how to do it. can anyone help me Here is the plunker http://plnkr.co/edit/zHMvBWCKevKgGeBerhhE?p=preview

3
are you looking for localStorage.setItem(key, value) and localStorage.getItem(key)? I don't know why you need ngStorage if you just want to use localStorage.AntiHeadshot
No, but the same thing. i have used ngStorage. github.com/gsklee/ngStorage , but i don't know , how to use it. If you can tell me in your own way. which you told above, that is also okThilak Raj

3 Answers

1
votes
// Getter
if ($window.localStorage.language) {
    $scope.language = $window.localStorage.language;
} else {
    $scope.language = 'en';
}


// Setter
$scope.setLanguage = function(language) {
    $scope.language = language;
    $window.localStorage.language = language;
}

To check your resource variables like cookies, local storage, etc. Under chrome developer tools (access with F12) go to Resources tab.

1
votes

You ca use:

window.localStorage['storageVariableName'] = language;

and if you want to save as jason format use

window.localStorage['storageVariableName'] = angular.tojson(language);

and access data

$scope.language = window.localStorage['storageVariableName'];
1
votes

ng-storage is amazingly simple.

Inject ngStorage in to your main module and $localStorage to your controller.

$scope.setLanguage = function(language) {
    $scope.language = language;    

    $localStorage.language = language;

   }

If you need to persist data across refreshes, think of using ng-cookies.

Inject ngCookies into your main module. Also insert $cookies into your controller.

Then you can use $cookies.put and $cookies.get for storing and retrieving data.

$scope.setLanguage = function(language) {
    $scope.language = language;    

    $cookies.put('language', language);

   }

Also note that you should use the cookie expiry date to set the TTL.