0

我已經寫了一個名爲lobInclude指令,我想同樣是ngInclude但沒有範圍:無子範圍自定義ngInclude指令 - 吳-消息不起作用

.directive("lobInclude", ["$templateRequest", "$compile", function($templateRequest, $compile) { 
     return { 
      restrict: "A", 
      scope: false, 
      compile: function() { 
       return { 
        pre: function(scope, elem, attrs) { 
         var toObserve = "lobInclude"; 
         attrs.$observe(toObserve, function(value) { 
          value = scope.$eval(value); 
          $templateRequest(value, true).then(function(response) { 
           if (angular.isDefined(attrs.replace)) 
            elem.replaceWith($compile(angular.element(response))(scope)); 
           else 
            elem.append($compile(angular.element(response))(scope)); 
          }); 
         }); 
        }, 
        post: function() { } 
       }; 
      } 
     } 
    }]); 

一切似乎都不錯,但NG-消息使用我的指令時不能正常工作,您可以在此處看到一個示例:http://codepen.io/jros/pen/jPxmxj?editors=101

在代碼筆中,我有一個帶有輸入和我的指令的表單,其中包含一個包含其他輸入的腳本ng-template。

第一個輸入中的ng消息正常工作,但沒有包含在我的include中。

有什麼想法嗎?

+0

爲什麼你需要lobInclude?使用ng-include將會起作用。 – milanlempera

+0

我需要在不創建子範圍的情況下包含模板,真正的例子比較複雜,需要從外部訪問模板的內容,反之亦然。 –

回答

0

的問題是關於請求的模板編譯:

$templateRequest(value, true).then(function(response) { 
    if (angular.isDefined(attrs.replace)) 
     elem.replaceWith($compile(angular.element(response))(scope)); 
    else 
     elem.append($compile(angular.element(response))(scope)); 
}); 

的secuence是:創建一個元素,編譯並添加/在DOM更換元件。調試angular.js我可以看到,NgModelDirective是誰與FormDirective控制器通信以設置$ pristine,$ touch,... NgModelDirective有一個'^?表單'作爲與父窗體交流的要求。 那麼,當我編譯元素時,模板沒有父窗體,因爲它不包含在DOM中。 ngModel找不到祖先形式,並且不能設置$錯誤,$質樸,$觸摸,...

解決的辦法是添加元素的DOM,然後編譯:

$templateRequest(value, true).then(function(response) { 
    var responseElem = angular.element(response); 
    if (angular.isDefined(attrs.replace)) 
     elem.replaceWith(responseElem); 
    else 
     elem.append(responseElem); 
    $compile(responseElem)(scope) 
}); 

謝謝