Custom directive with $ http injection angularjs

I want to create a widget using the angularjs custom directive, but got stuck somewhere by inserting $ http service into 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 to do this? I know that the code above does not work, but I do not know how to proceed.

+4
source share
1 answer

It should look like this:

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

app.directive('users', users);

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

function users($http){    
  return {
     restrict: 'E', // if it 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;
          });
     }
  };
}

Jsbin works here: http://jsbin.com/qepibukovu/1/edit?html,js,console,output

+4
source

Source: https://habr.com/ru/post/1652962/


All Articles