How to persist data and model in angular JS

蓝咒 提交于 2019-12-05 20:03:45

As comments have said, services and factories are both capable of this. I generally handle this using localStorageService like you have suggested. First, load the local storage module in your index.html AFTER angularJS, but BEFORE your app.js.

<script src="/angular/angular.js"></script>
<script src="/lib/angular-local-storage.js"></script>
<script src="/app.js"></script>

Next, include LocalStorageModule as a dependency in your main module's declaration.

angular.module('test',['LocalStorageModule']);

Now, configure locaStorageService in the relevant module's declaration file using:

localStorageServiceProvider
  .setStorageType('localStorage');

All together, your app.js file should resemble this:

angular.module('test',['LocalStorageModule']);

  config.$inject = ['localStorageServiceProvider'];
  function config (localStorageServiceProvider) {
  localStorageServiceProvider
      .setStorageType('localStorage');
  }

  angular
  .module('test')
  .config(['localStorageServiceProvider', config]);
  })();

I minify my scripts before they go into production, so I use dependency injection, specifically with the $inject syntax.

An example controller that loads your query from a cookie on page load, and saves your query to a cookie when you execute a search ($scope.doSearch):

(function () {

angular.module("pstat")
       .controller("homeCtrl", homeCtrl);

  homeCtrl.$inject = ['$log', 'dataService', 'localStorageService', '$http'];
   function homeCtrl ($log, dataService, localStorageService, $http) { {
     if (localStorageService.get("query")) { //Returns null for missing 'query' cookie
        //Or store the results directly if they aren't too large
        //Do something with your saved query on page load, probably get data
        //Example:
        dataService.getData(query)
        .success( function (data) {})
        .error( function (err) {})
     }
     $scope.doSearch = function (query) {
       vm.token = localStorageService.set("query", query);
       //Then actually do your search
     }
   })
}()

As long as your root URL does not change, you can access this cookie with either your query or your results on any page through localStorageService. If you need more details on anything just let me know.

Note if you want to do this automatically on page load, you need to wrap your controller in an Immediately Invoked Function Expression. Good luck! AngularJS has a fairly high learning curve, but is one of the most powerful front end software suites available.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!