如何使用AngularJS在ng-click上使用指令调用函数?

时间:2014-03-28 15:30:04

标签: javascript angularjs using-directives

我有一个指令,它从2个单独的$ http调用中获取数据并填充2个不同的ng-repeat。

为了减少服务器调用,我只是在点击第一个ng-repeat列表的某个元素时才进行第二次调用。

所以,现在我的指令默认进行2次调用,你可以在这里看到:

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

结果存储在Factory中,并从Controller调用,如下所示:

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

然后,我可以将第二个调用作为函数放在指令之外,并将其称为ng-click =“CallFunctionName”吗?我已经尝试过但它不起作用,所以也许我错过了一些东西。或者比这更复杂?

编辑:这是Plunker

0 个答案:

没有答案