usman usman - 1 month ago 8
AngularJS Question

How can I navigate between different views while maintaining views model data in angularjs

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.

Answer

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.