Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

angular local storage - How to use ngStorage in angularjs

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...