How to use ngStorage in angularjs

六眼飞鱼酱① 提交于 2019-12-29 05:00:08

问题


visit https://github.com/gsklee/ngStorage.

My code has 2 partials, in partial1 I've 3 input box and data entered in them be 'abc', 'pqr', 'xyz' and on click of button I want to get redirected to partial2 where input box gets populated with following details calculated in a controller 'abcpqr', 'abxy'.

Both partials uses localStorage [ngStorage] and in controller these values get calculated and gets pushed to partial2 on click of button [ng-click="functionName()"]. This function has logic to perform the calculations. how to do this?

In the app I'm creating i've 20+ such fields in both partials, so I don't want to pass values rather get them stored in localStorage and access from there.


回答1:


Assuming that you have ng-model attributes for all the fields that you're trying to capture in partial1 like below.

Partial-1

<input type='text' ng-model='pageData.field1' />
<input type='text' ng-model='pageData.field2' />
<input type='text' ng-model='pageData.field3' />

app.js

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

    myApp.controller('Ctrl1', function($scope, $localStorage){

        $scope.pageData = {};

        $scope.handleClick = function(){
           $localStorage.prevPageData = $scope.pageData; 
        };

    });

    myApp.controller('Ctrl2', function($scope, $localStorage){

        $scope.pageData = $localStorage.prevPageData;

    });

Partial-2

<p>{{pageData.field1}}</p> 
<p>{{pageData.field2}}</p> 
<p>{{pageData.field3}}</p> 

Another Approach :

But if you just want to send data from one controller in page1 to another controller in page2, you can do that with a service as well.

myApp.service('dataService',function(){

   var cache;

   this.saveData = function(data){
      cache = data;
   };

   this.retrieveData = function(){
      return cache;
   };

});

Inject this service in your first controller to save the page data and inject it again in your second controller to retrieve the saved page data.

myApp.controller('Ctrl1', function($scope, dataService){

   dataService.saveData($scope.pageData);

});

myApp.controller('Ctrl2', function($scope, dataService){

   $scope.pageData = dataService.retrieveData();

});


来源:https://stackoverflow.com/questions/33036026/how-to-use-ngstorage-in-angularjs

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