Ning Sia Ning Sia - 3 months ago 11
Ajax Question

Custom directive with $http injection angularjs

I want to make a widget by using angularjs's custom directive, but stuck somewhere injecting $http service in it.

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

app.directive('users',function($scope,$http){

return {


$http.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {

$scope.user = response.data;
})
}

})


Any thought how can it be done? I know above code doesn't work but I have no clue how to continue.

Answer

This should probably look like:

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

app.directive('users', users);

users.$inject = ['$http'];

function users($http){    
  return {
     restrict: 'E', // if it's element
     template: '<div><ul><li ng-repeat="user in users">{{user.name}}</li></ul>{{user}}</div>',  // example template
     link: function($scope){
        $http.get('https://jsonplaceholder.typicode.com/users')
          .then(function(response) {
             $scope.users = response.data;
          });
     }
  };
}

Here's a working jsbin: http://jsbin.com/qepibukovu/1/edit?html,js,console,output

Comments