0

I have a problem when I make navigation from page1.html to page2.html in angularjs and then return back to page1.html my page model data is gone, how can I preserve that, kindly help me in this matter.

I have seen some similar questions but could not get the understanding how to achieve this task in AngularJS using services.

Usman
  • 2,547
  • 31
  • 35

4 Answers4

2

If i understand correctly , you want to share some state across two different views of your application. There are many ways to achieve this, as you stated above you can use a service.

var app = angular.module('myApp', []);
app.service('myService', function(){
  var data;
  this.setData = function(d){
    data = d;
  }
  this.getData = function(){
    return data;
  }
});

app.controller('myCtrl1', function($scope, myService){
 $scope.data = myService.getData();
 //do something
});

app.controller('myCtrl2', function($scope, myService){
 $scope.data = myService.getData();
 //do something
});

Services are singleton, are instantiated once and then cached by angular, everytime you need that specific data you can inject the service and call the methods provided.

Karim
  • 8,454
  • 3
  • 25
  • 33
0

Use local storage concept in your code, it will store all data in your browser, when you navigate the page then you can get all data from your browser. check sample code below.

<html ng-app="app">

  <head>
    <script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>

    <script>
      angular.module('app', [
        'ngStorage'
      ]).

      controller('Ctrl', function(
        $scope,
        $localStorage
      ){
        $scope.$storage = $localStorage.$default({
          x: 42
        });
      });
    </script>
  </head>

  <body ng-controller="Ctrl">
    <button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> + <button ng-click="$storage.y = $storage.y + 1">{{$storage.y}}</button> = {{$storage.x + $storage.y}}
  </body>

</html>
Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
0

Try to set both HTML on same app so that data won't lose.use routing views to display both HTML,


If you change HTML from one to another definitely data loss will happen ,angular frame-work only for single page apps....

Ramesh M
  • 35
  • 1
0
app.run(function($rootScope) {
    $rootScope.name="something";
});
//Controller
app.controller('myController',function ($scope,$rootScope){ 
console.log("Name in scope ",$scope.name);
});