angularjs maintain the scope variable across routes
Asked Answered
D

4

5

How do I maintain the model across routes. for eg I have a list of profiles loaded onto the home page. The home page also contains a "load more" action to load more profiles, basically pushing data to the model. On clicking of a specific profile, the detail-view for that profile is activated via routes. The detail view has a back button which redirects the user back to the home page. On routing back to the home page data(profiles) loaded by the "load more" action is lost. I need to maintain the model with the "load more" prepended data

Below is the code used

/* Controllers */
var profileControllers = angular.module('profileControllers', ['profileServices'])


profileControllers.controller('profileListCtrl', ['$scope','$location', 'Profile','$http',
  function($scope,$location, Profile,$http) {
    $scope.Profiles = Profile.query(function(){

        if($scope.Profiles.length < 3) {
                    $('#load_more_main_page').hide();
                }
        });
    $scope.orderProp = 'popular';
    $scope.response=[];

    //LOADMORE
    $scope.loadmore=function()
    {

        $http.get('profiles/profiles.php?profile_index='+$('#item-list .sub-item').length).success(function(response){
            if(response) {
                var reponseLength = response.length;
                if(reponseLength > 1) {
                    $.each(response,function(index,item) {


                         $scope.Profiles.push({
                                            UID: response[index].UID,
                                            id: response[index].id,
                                            popular: response[index].popular,
                                            imageUrl: response[index].imageUrl,
                                            name: response[index].name,
                                            tags: response[index].tags,
                                            category: response[index].category
                                        });

                        });
                }
                if(reponseLength < 3) {
                    $('#load_more_main_page').hide();
                }
            }

        });


    }

  }]);





  /* App Module */

var profileApp = angular.module('profileApp', [
  'ngRoute',
  'profileControllers',
  'profileServices',
]);



profileApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/profiles', {
        templateUrl: 'partials/profile-list.html',
        controller: 'profileListCtrl',
        resolve: {
            deps: function ($q, $rootScope) {
                var deferred = $q.defer();
                var dependencies = ['js/sort.js'];
                $script(dependencies, function () {
                    $rootScope.$apply(function () {
                        deferred.resolve();
                    });
                });
                return deferred.promise;
            }
        }
      }).
      when('/profiles/:profileId', {
        templateUrl: 'partials/profile-detail.html',
        controller: 'profileDetailCtrl',

      }).
      when('/profiles/cat/:category', {
        templateUrl: 'partials/profile-list-category.html',
        controller: 'profileCategoryListCtrl',

      }).
      when('/create/', {
        templateUrl: 'partials/profile-create.html',
        controller: 'profileCreateCtrl',
        css: ['css/createprofile.css','css/jquery-ui-1.10.4.custom.min.css','css/spectrum.css'],

      }).
      otherwise({
        redirectTo: '/profiles'
      });
  }]);
Disfigure answered 30/4, 2014 at 21:0 Comment(2)
Sounds like you need ui-router, which maintain view state. github.com/angular-ui/ui-routerWarn
@MikeRobinson I have added the code used in the application into my question, could you please guide how can I maintain the list-view model with prepended data from the load more call to action on routing back from detail view to list view?Disfigure
G
6

A service is generally the accepted way to share data between views. Because it's a singleton and isn't regenerated on route change, you can "cache" data there and retrieve it from any controller that the service is injected into.

The second answer of this question explains it with code:

Same data in multiple views using AngularJS

Greenland answered 30/4, 2014 at 21:4 Comment(1)
I have added the code being used in the question, my concern is the loadmore data, on returning back to the list view from the detail view of a profile, how do i maintain the model with the "load more" data previously prepended before coming to he detail viewDisfigure
D
1

Create an Angular service and pass it around the different routes.

Detailed answer here - https://mcmap.net/q/138028/-maintain-model-of-scope-when-changing-between-views-in-angularjs

Doldrums answered 30/4, 2014 at 21:4 Comment(0)
P
0

You can use an AngularJS service to do that. Services are singletons and can store data across route changes.

myModule.factory('serviceId', function() {
  var shinyNewServiceInstance = {
    // your data here
  };
  return shinyNewServiceInstance;
});

And use it in your controller:

controller('MyController', function($scope, serviceId) {
  // use serviceId here
});
Pestalozzi answered 30/4, 2014 at 21:2 Comment(6)
I am using a service, to load initial data onto the homepage i.e the list. loadmore does a call via $http.get that pushes data to the model. How do I link this to the detail view, it be great if you could provide an example.Disfigure
in the controller of your detail view reference the service (as shown in the example for MyController and serviceId). You can access the data present in the service across controllers. If not clear you might provide more details on your sources.Pestalozzi
I have updated the question to contain the controller,loadmore, service code usedDisfigure
move the $http.get(...) to your service and cache the results there. If still unclear you might create a plnkr.coPestalozzi
I have created a plunker plnkr.co/edit/JBj5wV20ZlPnTOCTPwsL?p=catalogue I wasn't sure about uploading the php file and database. Can you play along with dummy data. here is a sample of object returned { UID: 1, id: 1, popular: 30, imageUrl: "media/images/profile/3.jpg", name: "Dillion Stac", tags: [ "#anger", "#damn", "#smart" ], category: [ "expression" ] }Disfigure
how do I move the $http.get(...) to the service. Is there anything I can read on for implementation of the sameDisfigure
H
0

You're loosing the $scope variables because in Angular a controller is not a singleton. There will be a new instance of it generated when you navigate back.

If you want to store any kind of variables between route-changes, you can create a service to do it.

Hittel answered 30/4, 2014 at 21:3 Comment(3)
I have added the code used in the application, could you please guide how do I maintain the model with prepended data from "loadmore" on routing back from the detail view to the list viewDisfigure
There are 3 other answers providing links to resources about how to use services. If you have any specific questions after looking at those and trying to implement a solution I might be able to help, but please fix my code is not a specific question. What did you try after reading the links in the other answers?Hittel
I am currently trying to use the service for loadmore as well, on doing that I plan to share the service with the detail view controller. I am guessing by doing so I will be able to share data across the routes via the service. Still working on itDisfigure

© 2022 - 2024 — McMap. All rights reserved.