angularjs - How to provide delay in ng-controller -


as html page gets loaded, calls supercategorycontroller, assigning supercategories $scope variable.

$scope.supercategories = supercategoryservice.getsupercategories(); 

but controller depends on service, in turn calls http request. @ time pf assignment http request not completed. $scope.supercategories getting assiged 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 retrieve super categories' + error.message;         });       //simply returns 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 solve problem in proper way.

i haven't tried code myself approach solution using factory , promise make sure data has been loaded. 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) {                     // data should loaded here                     console.log(d.data);                     $scope.supercategories = d.data;                 }             })             .error(function(data, status) {                 // errors here             });     }  }]); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -