Matoy Matoy - 1 month ago 23
AngularJS Question

localStorage with angularJS - how to dynamic bind value to all tabs in browsers

I am having 2 file, index.html and server.js.

I am using localstorage to save text between tabs. my code is below.
2 questions:
1. will this be saved if I will close the browser (if I will turn down the computer?).
2. how can I change this code to dymanic change the value in all the open tabs? currently it just disaplay the new value when I open a new tab/press refresh on an old tab...

Thanks

index.html

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<h1></h1>
<h2>Current LocalStorage value is = {{ msg }} </h2>
<input type="text" ng-model="value">
<input type="button" value="save value" ng-click="update(value)">
</body>
</html>


script.js

var app;
app = angular.module("app", []);
app.controller("mainCtrl", function(myLocalStorage, $scope) {

$scope.msg = myLocalStorage.getData();

$scope.update = function(msgContent) {
$scope.msg = myLocalStorage.setData(msgContent);
};

});
app.factory("myLocalStorage", function($window) {
return {
setData: function(val) {
$window.localStorage && $window.localStorage.setItem('my-storage', val);
return val;
},
getData: function() {
return $window.localStorage && $window.localStorage.getItem('my-storage');
}
};
});

Answer
  1. Yes. It will.
  2. You should subscribe on storage change event

    $window.on('storage', this.onStorageChanged);