gpt4 book ai didi

javascript - AngularJs 的 templateUrl : Url or ID?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:30 24 4
gpt4 key购买 nike

AngularJS 文档提供了一个 templateUrl 示例:

使用:

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

在 Controller 中:

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

其中 my-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 如何知道它是外部文件还是 Tag 元素 ID?以及如何将其强制为某种类型?

(附注 - 未在 docs 中找到它)。

最佳答案

我将添加@QuarK 开头的内容,也许会填写更多细节。

$templateCache 在解析(内联或从文件)后用作模板的存储库。

source带有 text/ng-templatesscript 标签看起来像这样:

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,那么angular puts将内容放入由 templateUrl 索引的 $templateCache

像这样使用 script 标签最近才被引入到 Angular 中。因此,这是一个允许内联定义而不需要外部文件的选项。然而,在底层,一旦解析,两者都使用相同的机制来读取和编译 ($templateCache)。

希望这对您有所帮助。

关于javascript - AngularJs 的 templateUrl : Url or ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21451787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com