1

what do you think of the approach to create directives that expose services?

Example have a directive to do then get requests the UI would have just that:

<api-http id="clients" uri="rest/clients"></api-http>

<button ng-click="clients.get()">search clients</button>

<table>
<tr ng-repeat="client in clients.results.data"> 
<td>{{client.name}}</td>
</tr>
</table>

api-http is a policy that exposes an api rest via ui, the button I call the api which was exposed in the id, calling the get that stores the result in api under the variable result, and display the resultsenter code here in the table below, which They think of this approach?

this does not exempt the use of the controller as we could have a controller and the controller to call the api visual component.

1 Answers1

0

Such a directive could look something like this:

.directive('apiHttp', function($http) {
  return {
    link: function(scope, element, attrs) {
      scope[attrs.id] = {
        results: null,
        get: function() {
          $http.get(attrs.uri).then(function(response) {
            this.results = response;
          }.bind(this))
        }
      }
    }
  };
});

Demo: http://plnkr.co/edit/30jPmH0gcGkjGlzVJuGd?p=preview

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • So what do you think of this approach? see that here the directive is being used to provide a component that is not visual, but behavioral (ajax request), and nothing prevents it from being used a controller, but in this case have a controller with this approach becomes trivial, we could have routes no controllers defined using only interface components to compose a more complex behavior. what do you think? – Carlos Alberto Apr 18 '16 at 18:35
  • There is already some api that has components that contains similar directives? I'm thinking about using this approach in oposition to use of a controller code. – Carlos Alberto Apr 18 '16 at 18:40