Ning Sia
Ning Sia

Reputation: 139

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.

Upvotes: 4

Views: 729

Answers (1)

krutkowski86
krutkowski86

Reputation: 1083

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

Upvotes: 4

Related Questions