Search code examples
angularjsangular-directive

Angular ajax working only with $timeout in directive


I have a directive which makes an ajax request. It's not work until I wrap it inside a $timeout like here:

return {
        restrict: 'E',
        scope : {
            param1: '=',
            param2: '='
        },
        templateUrl: "teams/views/myDirective.html",
        link: function($scope){
            $timeout(function(){
                $http.get(endPointUrl)
                    .success(function(result){
                        console.log(result)
                    })
                    .error(function(err){
                        console.log(err);
                    });
            }, 0);
        }
    };

Do anybody have the idea why? Thanks the answers in advance!


Solution

  • $http call just returns the promise. Following code may help you. Ideally, fetching data like operations should be done in services instead of directive's link function.

    app.service('myService', ['$http',
      function($http) {
        this.getData = function() {
          return $http({
            method: 'GET',
            url: 'http://httpbin.org/get',
            headers: {
              'Content-Type': "application/json"
            }
          }).
          success(function(data, status) {
            return data;
          }).
          error(function(data, status) {
            return "Request Failed";
          });
    
        }
      }
    ]);
    
    app.directive('appDirective', ['myService',
      function(myService) {
        return {
          link: function($scope) {
            myService.getData().then(function(data) {
              $scope.name = 'User, Data fetched as: ' + JSON.stringify(data);
            })
          }
    
        }
      }
    ])
    

    working example: http://plnkr.co/edit/stdJxAnHINORI06pPZJX?p=preview