Search code examples
javascriptangularjsangularjs-directiveangular-uiangular-ui-typeahead

Embed AngularJS directive in another directive


I'm trying to implement some custom functions of Bootstrap Typeahed in a new directive. Doing this, I need to embed the original Typeahed directive into mine, passing it, my parameters:

this is the original directive:

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

this is my custom directive:

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

and this is how I'm trying to implement it:

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

            }
        };
    }

I'm getting problems passing parameters from my directive to the original Typeahead directive, especially the "items". I got this error: Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "{{items}}".

Someone could help me to solve this?


Solution

  • I would try 'uib-typeahead=' + attrs.items + instead of 'uib-typeahead="{{items}}"'

    Typeahead is using a custom parser for that 'for in' syntax. https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/typeahead.js#L7