2014-01-30 35 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

相关问题