title: How to make the controller wait for factory response in angularjs?
body: <p>I am trying to get the response from factory to controller. but when i am calling a function of factory from controller, then the controller not waiting for its response. and giving "undefined".</p>
  
  <p><strong>here it is my controller.js</strong></p>
  
  <pre><code>app.controller('customerCommentsController',function($scope,$http,$stateParams,$sce,$timeout,Comments){     
  
  var commentsdata = '';
  
  Comments.init(1,5);
  
  $scope.total_comments = Comments.total();
  console.log($scope.total_comments); //undefined 
  
  $scope.positive_comments = Comments.positive();
  console.log($scope.positive_comments);  //undefined 
  
  $scope.commentsdata = Comments.getcomments(1,30);       
  console.log($scope.commentsdata);   //undefined     
  });
  </code></pre>
  
  <p>here I am calling init() method which gets the response from ajax, which   takes some time to execute , but before it could complete, the other 2 statement   (total() and positive() method) execute below the init method. and that not gets   initialize because of init method not completed. and that why I am getting   undefined.
      and same problem is coming when I am calling getcomments method which doesn't wait for its response. </p>
  
  <p><strong>here it is my factory</strong> </p>
  
  <pre><code>app.factory("Comments",function($http,$timeout,$q){
  
  var commentshtml = [];
  var commentshtml1 = [];
  
  return {
      init :  function(start,end) {  
      var request = $http({   
              method:"post",
              url:"/comments.php",
              data: {start:start,end:end},                
              headers: {'Content-Type' : 'application/x-www-form-urlencoded'}                     
          });     
  
      request.success(function(data){                 
              commentshtml = data;            
          });             
      },      
      total : function() {
  
                  return commentshtml.total_comment;                    
      },
      positive : function(){
  
              return commentshtml.per_positive_comment;               
      },
      getcomments : function(start,end) { 
  
          var promise  = $http({  
              method:"post",
              url:"/comments.php",
              data: {start:start,end:end},                
              headers: {'Content-Type' : 'application/x-www-form-urlencoded'}                     
          });
  
          promise.success(function(data){                 
              commentshtml1 = data.comments;
              console.log(commentshtml1); //giving the object             
              return commentshtml1;   
          }); 
  
      }
  };
  </code></pre>