1

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.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Ed Staub
  • 15,480
  • 3
  • 61
  • 91
  • looks you need to manipulate DOM in compile `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]); } }` then compile it from postLink – Pankaj Parkar Jun 26 '15 at 18:48
  • @pankajparkar - Thanks, that worked very well, except that the typeahead directive doesn't then seem to work in my context - it doesn't complain, but doesn't activate. The cause may be irrelevant; I'm still trouble-shooting, in my spare time, since I've already spent days on this! %*&^%& If you want to write your comment up as an answer, I'll accept. Otherwise, I'll do it myself. If you have any pointers to helpful docs or posts re using nested directives, please include. – Ed Staub Jun 27 '15 at 15:58

1 Answers1

1

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

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299