Eric Mitjans
Eric Mitjans

Reputation: 2169

Passing data from directive to controller in AngularJS

I'm looking for a way (a function) to take data from a clicked element from an ng-repeat list and pass it into a controller.

My dirctive gets the data like so:

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.defaultFormat);
      })
      .error(function($scope) {
        scope.basicFormat = scope.release.format;
        dataService.setItems(scope.basicFormat);
     });

And it stores it in a factory:

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

On the controller side, the function will trigger getItems, but it just doesn't work.

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

Here's a Plunker. The list that appears under every album name should be appearing into the box that opens upon click, but the box will only show the data from the last element of the lit (the last data stored into the scope.basicFormat or scope.defaultFormat variables), so the conclusion I'm getting is that so far, the function won't trigger the setItems for each element.

Upvotes: 0

Views: 108

Answers (1)

vortexwolf
vortexwolf

Reputation: 14037

It's because you call musicInfoService.getReleaseVersions thousands times, but the dataService.setItems function doesn't distinguish these calls and always overwrites results. That's why only the last result is shown.

At first fix your data service factory so that it takes the key parameter:

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"];
          }
    };
}]);

Then update your setItems calls:

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

And update your getItems call:

$scope.versions = dataService.getItems($scope.release.id.toString());

After this your Plunker example works.

Upvotes: 1

Related Questions