1

I have made a directive that makes a dropdown and populates it from an API. It works. However when I used this directive multiple times in a view it makes multiple calls to the API to populate the dropdown.

So I was wondering if there was some simple way to avoid that. The not so simple way would be to put the $http into a service that does caching somehow.

Directive

app.directive('dropdown', function() {
    return {
        // omitted...
        controller: function($scope, $http) {
            $http.get("...")...;
        }
    };
});

View

<dropdown></dropdown>
<dropdown></dropdown>
Snæbjørn
  • 10,322
  • 14
  • 65
  • 124

1 Answers1

0

It's better to use a service to handle your $http requests and it will also allow you to cache data.

In this particular case you will keep your data in an object in the service and each time you load the directive and call the service method getMyData(blah) you will check if the data exists already in the object and cancel the call to the API, otherwise perform the $http.get.

bosch
  • 1,089
  • 11
  • 16