How to use ngStorage in angularjs

后端 未结 1 779
傲寒
傲寒 2020-12-15 13:59

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 o

相关标签:
1条回答
  • 2020-12-15 14:41

    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();
    
    });
    
    0 讨论(0)
提交回复
热议问题