Search code examples
angularjskendo-uikendo-dropdown

Directives doesn't translate attributes after element replace with jQuery


I tried to do directive, which include template on the fly, but there is one problem - after compile all attributes, including ng-model, aren't translate to new element and ng-model doesn't working. Where I'm wrong?

Element code:

<input type-test="kendo">

Directive:

    App.directive('typeTest', ['$templateCache', '$compile', '$http', 'Formatter',
        function ($templateCache, $compile, $http, Formatter) {
            return {
                restrict: 'A',
                scope: {
                    ngModel: '='
                },
                replace: true,
                link: function(scope, element, attrs) {
                    $http.get(Formatter.getTemplateUrl(attrs.typeTest), {cache: $templateCache}).success(function(tplContent) {
                        var el = $compile(tplContent)(scope);
                        element.replaceWith(el);
                    });
                }
            }
        }
    ]);

Formatter.getTemplateUrl() returns a url to template depend on input argument (attrs.typeTest).

Template to type-test="kendo":

<input type="text" kendo-drop-down-list k-data-source="list" k-data-text-field="'Name'" k-data-value-field="'Id'">

List is defined like [{Id: 1, Name: 'First'}, {Id: 2, Name: 'Second'}].


Solution

  • I find a solution:

        App.directive('dynamicType', ['$compile',
            function ($compile) {
                return {
                    compile: function compile(tElement, tAttrs, transclude) {
                  return {
                    pre: function preLink(scope, iElement, iAttrs, controller) { 
                                var tpl = "<input type-test='"+iAttrs.dynamicType+"'>";
                                iElement.html(tpl);
                                $compile(iElement.contents())(scope);
                     },
                    post: function postLink(scope, iElement, iAttrs, controller) {}
                  }
                    }
                }
            }
        ]);
    

    This directive compile new element, then link it and after return control to typeTest directive - to compile and link other element.

    Element:

    <input dynamic-type="kendo">