在另一个指令中嵌入AngularJS指令

Embed AngularJS directive in another directive

本文关键字:指令 AngularJS 另一个      更新时间:2023-09-26

我正试图在一个新指令中实现Bootstrap Typeahed的一些自定义函数。为此,我需要将原始的Typeahed指令嵌入到我的指令中,并将其传递给我的参数:

这是最初的指令:

<div class="typeahead typeahead-lookup">
    <input ng-model="vm.myModel" 
           uib-typeahead="item as item.Formatted for item in vm.refreshSearch($viewValue)"
           typeahead-wait-ms="1000"
           typeahead-min-length="1"
           typeahead-editable="false"
           placeholder="SEARCH..."
           type="text"
           class="form-control">
</div>

这是我的自定义指令:

<select-lookup model="vm.myModel" 
               items="item as item.Formatted for item in vm.refreshSearch($viewValue)" 
</select-lookup>

这就是我试图实现它的方式:

function selectLookup($compile) {
        return {
            restrict: 'E',
            scope: {
              model: "=",
              items: "@"
            },
            compile: function(element, attrs) {
                return function(scope, element, attrs) {
                    var template = '<div class="typeahead typeahead-lookup">' +
                                        '<input ng-model="model"' +
                                               'uib-typeahead="{{items}}"' +
                                               'typeahead-wait-ms="1000"' +
                                               'typeahead-min-length="1"' +
                                               'typeahead-editable="false"' +
                                               'placeholder="SEARCH..."' +
                                               'type="text"' +
                                               'class="form-control">' +
                                   '</div>';
                    element.html(template);
                    $compile(element.contents())(scope);
                };
            }
        };
    }

将参数从指令传递到原始Typeahead指令时遇到问题,尤其是"items"。我得到了这个错误:Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "{{items}}"

有人能帮我解决这个问题吗?

我会尝试'uib-typeahead=' + attrs.items +而不是'uib-typeahead="{{items}}"'

Typeahead正在为"for in"语法使用自定义语法分析器。https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/typeahead.js#L7