2014-01-30 39 views
3

AngularJS文檔提供templateUrl例如AngularJs的templateUrl:網址或ID?使用</p> <p>:

//ngApp... 
<div ng-controller="Ctrl"> 
     <div my-customer></div> 
    </div> 

和Controller:

....directive('myCustomer', function() { 
    return { 
     templateUrl: 'my-customer.html' 
    }; 
    }) 

凡我-customer.html是外部文件:

enter image description here

一切都好。但他們提供了編輯它的選項(通過jsfiddle):

但是,它就像模板標籤! :

<div ng-app="docsTemplateUrlDirective"> 
    <div ng-controller="Ctrl"> 
    <div my-customer></div> 
    </div> 



     <!-- my-customer.html --> 
     <script type="text/ng-template" id="my-customer.html"> 
     Name: {{customer.name}} Address: {{customer.address}} 
     </script> 
    </div> 

問:

如何NG知道,如果它是一個外部文件還是一個標籤元素ID?以及我如何強制它達到某種類型?

(附註: - 沒有發現它在docs)。

回答

5

我會添加什麼@QuarK開始,也許在更多的細節填充。

$templateCache用作模板庫,一旦他們已經解決了(在線或文件)。

的的script標籤與text/ng-templatessource看起來是這樣的:

var scriptDirective = ['$templateCache', function($templateCache) { 
    return { 
    restrict: 'E', 
    terminal: true, 
    compile: function(element, attr) { 
     if (attr.type == 'text/ng-template') { 
     var templateUrl = attr.id, 
      // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent 
      text = element[0].text; 

     $templateCache.put(templateUrl, text); 
     } 
    } 
    }; 
}]; 

你可以看到,如果一個script標籤被發現,而attr.typetext/ng-template,然後角度提出的內容爲通過索引的$templateCachetemplateUrl

使用script標籤這樣最近才推出角。所以,這是一個允許內聯定義而不需要外部文件的選項。然而,在下面,一旦解決,兩者都使用相同的機制來讀取和編譯($templateCache)。

希望這會有所幫助。

+0

我怎樣才能迫使它來:「去到服務器,不看標籤?」 –

+0

你可以簡單地不叫兩個模板與相同的名字:) – QuarK

+0

不完全確定。您可以直接引用'$ templateCache'並進行刪除緩存。雖然我不確定這裏提供的粒度。這是一個鏈接:https://groups.google.com/forum/#!topic/angular/bxrpsImO0rY –

0

這是通過$ templateCache,你可以在它的API找到的文檔:

http://docs.angularjs.org/api/ng.$templateCache

+0

這不回答,如果角度找到你的腳本標記在呼喚一個模板,我可以想像的問題.... :-)(標籤VS ID) –

+0

好,模板被加載時,將要使用的,會詢問服務器是否與給定的文件名部分存在之前加載這個.. – QuarK

相關問題