Pablo Ivan
Pablo Ivan

Reputation: 280

Session Storage with AngularJS and ng-storage

I am developing a chat application. I have the next HTML:

<input type='text' id='nameInput' placeholder='Your Name'>

I'm also working with AngularJS, this is my module:

var app = angular.module('principal', ['ngStorage']);
app.controller('MainCtrl', function($scope, $sessionStorage) {
  $scope.$storage = $sessionStorage.$default(#nameInput);
});

As you can see, I have ngStorage as a dependency. I am trying to sessionStorage the input value, so if the user accidentaly refresh the page, his name stills written in the input, but my code doesn't work, what can I do?

UPDATE By now, thanks to Matt, I solved my doubt.

Upvotes: 1

Views: 1763

Answers (1)

Matt Way
Matt Way

Reputation: 33171

You need to bind your view, in this case your input element, to a value in your model. You do this using ng-model. For example:

<input type="text" ng-model="state.nameInput" placeholder="Your Name">

Then you just need to set your scope in your controller.

$scope.state = {
    nameInput: 'John'
};

If you want to instead want to use ngStorage as the binding (instead of a regular $scope value), try the following in your controller:

$scope.$storage = $sessionStorage.$default(/* any defaults here */);

And in your html

<input type="text" ng-model="$storage.nameInput" placeholder="Your Name">

Basically, what you are saying is; Put the $sessionStorage object directly on the $scope, so that the view can reference it, and its children. Then you tell the <input> that you want its value to reference a particular child on that scope using ng-model. So when you change a value on the input, it will change the scope model value, which in turn will update the session storage.

Upvotes: 1

Related Questions