Save $Scope from page with Angularjs

Asked

Viewed 721 times

2

I have a screen where some functionality is done via ajax on the page, so the user can make filters, etc;

By checking the result he wants, he can click on a link that will redirect him to a new page, but if he clicks on the back of the browser he will return to the previous page and will lose the filters he made.

I need to store the variable vm($scope-this) so that when I return I take this variable and seven again in the variable vm, but it’s not working because I store it in a Hidden.

Is there anything else I can try?

  • Have you thought about using Localstorage? Angular has a library for this.

  • Or if you use these filter arguments directly in the URL you can also keep the filter by turning the page

2 answers

1

As already said you can use the SessionStorage or LocalStorage. Angular already has a library that facilitates the use of both: ngStorage

All you need to do is save your filter to one of the two and then retrieve it where you want it. Example:

var myApp = angular.module('myApp', ['ngStorage']);

function MyCtrl($scope, $localStorage) {
    //Recupera o objeto que está no localStorage
    $scope.myFilter = $localStorage.filter;
    console.log($scope.myFilter);
  
    $scope.filtrate = function(data) {
        //Salva o objeto no localStorage
        $localStorage.filter = data;
        console.log($localStorage.filter);
    };
  
    $scope.clearStorage = function(){
      //Limpa o localStorage de nome filter
      delete $localStorage.filter;
      console.log($localStorage.filter);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.11/ngStorage.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
 <input type="text" ng-model="user.name" placeholder="Name"/>
 <input type="text" ng-model="user.age" placeholder="Age"/>
 <button ng-click="filtrate(user)">Filter</button>
 <button ng-click="clearStorage()">Clear Storage</button>
</div>

Like WebStorage is not supported on code snippet follows the example in jsfiddle

-1

There are several ways to do this, particularly I prefer to use services without a little code gets a little complicated help more. Depending on the situation you can put all the logic within the service.

In this case that makes a page Reload all really loses everything, the way would be something like the localstorage same, but maybe Oce is more interested in the Session Storage, which is the same thing, but unlike locastorage the data is erased as soon as the browser closes.

  • More if I use service it will not store the json object when I return from Brower because it will be reloaded as I do not have a static header with pages being opened inside. In my case the single page is loaded more as a whole

Browser other questions tagged

You are not signed in. Login or sign up in order to post.