4

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.

2
  • Your function should return an object with the properties of your directive (restrict, template, etc.). Please read the directive tutorial on Angular website. If you need to execute some code when the directive binds, it can be done in thelink method. Commented Aug 30, 2016 at 8:25
  • @Impworks are there compulsory? Commented Aug 30, 2016 at 8:40

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

jsbin.com/jaweqihoyu/edit?html,js,console,output nope it's not working. why you no need ng-repeat?
There should be one more bracket '}'. Check it now as above.
what if I want to display the user's name in a <li>, I can do the same like usual?
why do u use $inject? what's the problem with my injection above? like just pass $http as a param.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.