0

I've a directive that gets data from 2 separate $http calls and populates 2 different ng-repeat.

In order to reduce the server calls, I'm looking into making the second call only upon ng-click of a certain element of the first ng-repeat list.

So, right now my directive makes the 2 calls by default, as you can see here:

var app = angular.module('myApp');


app.directive('release', ['musicInfoService', 'dataService',
  function(musicInfoService, dataService) {

    return {
      restrict: 'E',
      scope: {
        release: '=',
        artist: '='
      },
      template: '<div class="release">' +
        '<div class="wrapper"><img class="img-responsive" ng-src="{{imageSrc}}"/><div id="text" ng-click="VersionController($scope, dataService)"></div></div>{{release.title | characters:45}}' +
        '</div>',
      replace: false,
      link: function(scope, elem, attr) {
        var defaultImage = 'img/record-default.png';

        scope.imageSrc = defaultImage;
        musicInfoService.getAlbumInfo(scope.artist.name, scope.release.title)
          .success(function(data) {
            if (data.error) return;

            var image = data.album.image[2],
              imageUrl = defaultImage;

            if (image['#text'] !== '') {
              imageUrl = image['#text'];
            }

            scope.imageSrc = imageUrl;
          });

        var defaultFormat = scope.release.format;
        musicInfoService.getReleaseVersions(scope.release.id)
        .success(function(data) {
            if (data.error) return;

            var format = data.versions,
              formats = scope.release.format;

            if (format !== '') {
              formats = format;
            }

            scope.defaultFormat = formats;
                dataService.setItems(scope.release.id.toString(), scope.defaultFormat);
            })
            .error(function($scope) {
                scope.defaultFormat = false;
                dataService.setItems("basic", scope.defaultFormat);
            });
      }
    };
  }
]);

app.factory('dataService', [function($scope){
    var _items= {};
    return { 
          setItems:function(key, value){
             _items[key] = value;
          },
          getItems:function(key){
             return _items[key] ? _items[key] : _items["basic"];
          }
    };
}]);

The results are stored into the Factory and called from the Controller like so:

function VersionController($scope, dataService) {
  $scope.versions = dataService.getItems($scope.release.id.toString());
  console.log($scope.versions);
}

Then, could I place the second call outside the directive as a function and call it like ng-click="CallFunctionName"? I've tried already but it doesnt work, so maybe I've missed something. Or is more complicated than that?

EDIT: Here's a Plunker!

Eric Mitjans
  • 2,149
  • 5
  • 40
  • 69

0 Answers0