2014-03-31 47 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">