Frage

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'}].

War es hilfreich?

Lösung 2

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

Andere Tipps

You shouldn't replace the element inside a linking function of a directive. The linking function should just set up event listeners to make the directive work. Place your logic inside the compile function instead of the link function. Here's a pretty good article about it: http://amitgharat.wordpress.com/2013/06/08/the-hitchhikers-guide-to-the-directive/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top