Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 841
surbhi bakshi Avatar asked Dec 06 '22 20:12

surbhi bakshi


1 Answers

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

});
like image 131
Arkantos Avatar answered Jan 22 '23 08:01

Arkantos