Arepalli Praveenkumar
Arepalli Praveenkumar

Reputation: 1306

Server requests in Angular Directive?

I am going to write a Angular Custom Directive

PROPOSSED BY MY LEAD

index.html

    <users-list resource-url="getUsersList"></user-list>

Script :

    .directive(usersList, function ($http) {
       return {
          restrict :'E',
          scope : {
              resourceUrl : '@' 
                  },
          templateUrl : "someTemplate.html",
          link : function (scope, ele, attr) {
               $http.get(scope.resourceUrl).success(function (list) {
                 scope.users = list;
              });
            } 
        };        
     });

someTemplate.html

     <div ng-repeat="user in users">{{user.name}}</div>

MY OBSERVATOIN

like

   <users-list list="usersList"></users-list>

QUESTION

Is it good idea to write server requests in directive itself?

Upvotes: 1

Views: 365

Answers (1)

İlker Korkut
İlker Korkut

Reputation: 3250

This might be a good idea but in my opinion it's not good practise for angularjs.

You should wrap your request in your angularjs service(factory) and then inject your service to your directive to make http call , also you can give resource url for your service via directive with an html attribute on your element.

Upvotes: 4

Related Questions