1

As soon as Html page gets loaded, it calls SuperCategoryController, where i am assigning supercategories to $scope variable.

$scope.SuperCategories = SuperCategoryService.GetSuperCategories();

But as this controller is depends on service, which in turn calls the http request. so at the time pf assignment http request is not completed. so $scope.SuperCategories is getting assiged to undefined.

sampleApp.service('SuperCategoryService', ['$http', function ($http){

    var URL = 'http://localhost/cgi-bin/superCategory.pl';
    var SuperCategories;

    $http({
            method: 'POST',
            url: URL,
            data: "action=GET",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).
        success(function (data) {
            alert (data);
            if (data != null || data != 'undefined') {
                SuperCategories = data;
            }   

        })
        .error(function (error) {
            alert (error.message);
            //$scope.status = 'Unable to retrieve super categories' + error.message;
        }); 

    //simply returns the SuperCategories list
    this.GetSuperCategories = function () {
        //alert (SuperCategories);
        return SuperCategories;
    }
}]);



sampleApp.controller('SuperCategoryController', ['$scope', 'SuperCategoryService', function ($scope, SuperCategoryService){

    $scope.SuperCategories = SuperCategoryService.GetSuperCategories();

    $scope.LoadSuperCategoryMapping = function()
    {
        alert ($scope.SelectedSuperCategory.id);
    }

}]);

How to solve this problem in proper way.

1 Answer 1

4

I haven't tried this code myself but I would approach a solution using factory and a promise to make sure the data has been loaded. Something along these lines:

sampleApp.factory('SuperCategoryService', ['$http', function ($http){

    return {

        GetSuperCategories: function () {

            var URL = 'http://localhost/cgi-bin/superCategory.pl';
            return $http.get(URL);
        }

    }

}]);



sampleApp.controller('SuperCategoryController', ['$scope', 'SuperCategoryService', function ($scope, SuperCategoryService){

    $scope.SuperCategories = function() {

        SuperCategoryService.GetSuperCategories()
            .then(function(d) {
                if (d.data != undefined) {
                    // Your data should be loaded here
                    console.log(d.data);
                    $scope.SuperCategories = d.data;
                }
            })
            .error(function(data, status) {
                // Errors here
            });
    }

}]);

Not the answer you're looking for? Browse other questions tagged or ask your own question.