2014-03-31 56 views
0

我試圖做指令,其中包含模板,但存在一個問題 - 編譯所有屬性後,包括ng-model在內,不會轉換爲新元素而ng-model不起作用。 我哪裏錯了?使用jQuery替換元素後,指令不會轉換屬性

元素代碼:

<input type-test="kendo"> 

指令:

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()返回的URL模板依賴於輸入參數(attrs.typeTest)。

模板鍵入測試= 「劍道」:

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

列表被定義如[{ID:1,名稱: '第一'},{ID:2,名稱: '第二'}] 。

回答

0

我找到一個解決方案:

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

這個指令編譯新的元素,然後連接並返回控制到typeTest指令之後 - 編譯和鏈接等元素。

元素:

<input dynamic-type="kendo">