在指令中使用ngOptions

时间:2013-01-29 15:21:47

标签: angularjs angularjs-directive

我有以下穿梭盒指令:

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

我的模板如下所示:

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>'

我想要做的是从<shuttle-boxes>获取ng-options转发器并使用它来填充<select class="shuttle-boxes-left">

我尝试这样做的方法是无效的只是将ng-options属性复制到选择列表中,如下所示:

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

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

这是小提琴:http://jsfiddle.net/dkrotts/tHTAY/1/

我做错了什么?

1 个答案:

答案 0 :(得分:8)

我建议您只将itemList传递给指令(和myModel),并将ng-options放在模板中:

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

指令:

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