Skip to content Skip to sidebar Skip to footer

Angular Pass Data Between Controller

I have requirement where i need to share data between controllers,so i created factory suppose i have url like: abc/123 (Note:123 is dynamic i need to pass it from controller) MyCo

Solution 1:

Solution 2:

The easiest solution is to just enable caching in your service. This way all your controllers can access the method and the request is made only once.

return $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true', {cache: true});

This is very basic caching. You may need a more advanced strategy -- but this is your first step.

UPDATE

You may run into a race condition with simple $http caching if your second or third request are made before the first request completes. We can overcome this easily.

appServices.factory('classesService', function($http) {

    var orgsPromise;    

    return {
        getClasses: function(value) {

            if (orgsPromise) return orgsPromise; 

            orgsPromise = $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true');

            return orgsPromise;
        }
    };
});

Solution 3:

I believe you can do something like this;

var yourApp = angular.module('yourApp',[]);

yourApp.factory('classesService', function($http){
    var classes;  
    return {            
        getClasses: function(value) {
            if (!classes) {
                classes= $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true');
            }
            return classes;
        }
    };
});

yourApp.factory('Classes', ['classesService',function(classesService){
    return classesService.getClasses();
}]);

functionyourControllerA($scope, Classes) {
    $scope.value="Hello from Controller A"; 
    $scope.sharedValue=Classes;
    ....
}

functionyourControllerB($scope, Classes) {
    $scope.value="Hello from Controller B"; 
    $scope.sharedValue=Classes;
    ....
}

functionyourControllerC($scope, Classes) {
    $scope.value="Hello from Controller C"; 
    $scope.sharedValue=Classes;
    ....
}

Post a Comment for "Angular Pass Data Between Controller"