在ng-repeat中创建指令

时间:2014-04-29 20:59:24

标签: angularjs directive

我有一个指令,我想用它来生成其他指令。以下不起作用:

    <span ng-repeat="picker in pickers | filter:{type:'click'}">
      <span picker.name></span>
    </span>

如何使用 picker.name 在此ng-repeat中创建更多指令?

- 背景

我们有一个主要的'选择器服务',它注入了几个服务'选择器Local','picker Dropbox','picker Googledrive'。

function pickerService($filter, pickerDropboxService, pickerGoogledriveService, pickerLocalService){
    // list pickers
    this.pickers = [pickerDropboxService, pickerGoogledriveService, pickerLocalService];
}

我们有一个选择器指令,它基本上遍历拾取器并尝试为每个选择器创建一个自定义指令:

        <span ng-repeat="picker in pickers">
          {{picker.name}}
          <span {{picker.name}}></span>
        </span>

每个选择器(Local,Dropbox,Googledrive)声明一个指令,我想从我的主选择器指令中使用该指令。

由于

1 个答案:

答案 0 :(得分:1)

最好的解决方案似乎是使用&#39;编译&#39;在指令中:

<强> directive.html:

<span id='pickerButtons'></span>

<强> directive.js:

    'compile': function(element, attributes) {

        var pickerButtons = document.querySelector('#pickerButtons');
        var span = document.createElement('span');
        span.innerHTML = '';

        for (var i=0,  tot=pickerService.pickers.length; i < tot; i++) {
            if(pickerService.pickers[i].type === 'button'){
                span.innerHTML += '<span><span picker-' + pickerService.pickers[i].name + '></span></span>';
            }
        }

        pickerButtons.appendChild(span);

        var linkFunction = function($scope, element, attributes) {
            $scope['pickFrom'] = function(pickerObject){pickerService.pickFrom(pickerObject);};
            $scope['pickList'] = pickerService.getPickList();
        };

        return linkFunction;
    }