AngularJS : invoking optional nested directive on template sub-element

196 views Asked by At

I'm trying to write a directive that emits all of the HTML for a field in a form - the wrapping div, label, input, etc. For some fields I want to use Angular UI Bootstrap's "typeahead" directive.

I first tried using, in the template, a ng-attr-typeahead='{{myTypeahead}}'. I expected that, on the fields where 'myTypeahead' is not set, that there would be no evidence of a "typeahead" attribute. Instead, during directive processing, the attribute is present in the attribute list with an undefined value, and the typeahead directive is invoked and promptly blows up because its input is undefined.

I then tried using a postcompile function like so:

    compile: function compile(tElement, tAttrs, transclude) {
        return function postLink(scope, iElement, iAttrs, controller) {
            if ( iAttrs.eiTypeahead !== undefined ) {
                var me = $(iElement);
                var input = $("input", me);
                input.attr("typeahead", iAttrs.eiTypeahead);
                $compile(input[0]);
            }
        }
    }

This puts the "typeahead" attribute on the input element, but does not invoke the typeahead directive.

I expect this is probably a duplicate of some other post, but I'm not searching on the right words to find it.

1

There are 1 answers

0
Pankaj Parkar On BEST ANSWER

While you are adding other directive to the your directive element then those should added from the compile function of your directive and you could compile directive element from the postLink function which return from the compile.

Code

compile: function compile(tElement, tAttrs, transclude) {
    if ( iAttrs.eiTypeahead !== undefined ) {
       var me = $(iElement);
       var input = $("input", me);
       input.attr("typeahead", iAttrs.eiTypeahead);
    }
    return function postLink(scope, iElement, iAttrs, controller) {
        $compile(input[0]);
    }
}

You could refer this answer for better explaination