Using ngOptions inside directive

若如初见. 提交于 2019-12-23 09:26:56

问题


I have the following shuttle boxes directive:

<shuttle-boxes ng-options="item for item in itemList" ng-model="myModel" />

My template looks like this:

template: '<div class="shuttle-boxes">' +
        '<select multiple="multiple" class="shuttle-boxes-left"></select>' +
        '<button class="shuttle-boxes-btn" type="button"><i class="icon icon-arrow-right"></i></button>' +
        '<button class="shuttle-boxes-btn" type="button"><i class="icon icon-arrow-left"></i></button>' +
        '<select multiple="multiple" class="shuttle-boxes-right"></select>' +
        '</div>'

What I want to do is take the ng-options repeater from <shuttle-boxes> and use it to populate <select class="shuttle-boxes-left">.

The way I am trying to do it that isn't working is simply copying over the ng-options attribute to the select list like so:

var availableList = cElement.find('.shuttle-boxes-left'),
        repeater = cAttrs.ngOptions;

    availableList.attr('ng-options', repeater);

Here is the fiddle: http://jsfiddle.net/dkrotts/tHTAY/1/

What am I doing wrong?


回答1:


I suggest you only pass the itemList to the directive (and myModel) and put the ng-options inside your template:

 <shuttle-boxes items="itemList" ng-model="myModel"></shuttle-boxes>

Directive:

myApp.directive('shuttleBoxes', function($timeout) {
    return {
        restrict: 'E',
        scope: { items: '=', ngModel: '='},
        template: '<div class="shuttle-boxes">' +
            '<select multiple="multiple" class="shuttle-boxes-left" 
               ng-options="item for item in items" ng-model="ngModel"></select>' +
            '<button class="shuttle-boxes-btn" type="button">' +
            '<i class="icon icon-arrow-right"></i></button>' +
            '<button class="shuttle-boxes-btn" type="button">' +
            '<i class="icon icon-arrow-left"></i></button>' +
            '<select multiple="multiple" class="shuttle-boxes-right"></select>' +
            '</div>',
        replace: true
    }
});

Fiddle.



来源:https://stackoverflow.com/questions/14586249/using-ngoptions-inside-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!