gpt4 book ai didi

javascript - 如何使 templateUrl 为 null 或未定义或空字符串的指令

转载 作者:行者123 更新时间:2023-11-28 00:53:12 24 4
gpt4 key购买 nike

我正在尝试实现一个针对下拉菜单通用的指令。我通常传递具有大模板的菜单的 templateUrl。但也有一些小菜单,例如“ul”标签中的 3 个“li”。我不想创建一个单独的模板来使用 templateUrl 进行调用,我只想使用实现指令的元素内的 html 来实现功能。

return {
restrict : 'A',
templateUrl: function(element,attrs){
return (attrs.templateUrl)? attrs.templateUrl : null;
},
scope:"",
link: function (scope, element, attrs) {

}
}

这就是我正在做的事情,但在加载模板时出现错误。这里有什么工作吗?

目标 = 如果作为 templateUrl 传递则渲染模板,或者如果 templateUrl 未作为属性传递则仅使用指令元素内的元素

最佳答案

我正在制作自己的框架,我遇到了和你一样的情况。所以我写了一个执行动态模板 url 的模块。如果没有定义元素或默认 templateUrl ,它会将元素的内部内容作为字符串存储在以随机生成的 key 命名的 $templateCache 服务中,然后如果您设置它动态地作为指令的 templateUrl 属性,其元素的内容将与您最初编写的相同。我不知道这是否是一个完美的解决方案,但对我来说已经足够了:

该模块(抱歉,我无法托管它,我的工作信息安全阻止了所有)

(function(){
var moduleName = "templateManager",
serviceName = "TemplateManager",
NAMES = {
ATTR_NAME: "templateUrl",
TEMPLATE: "templateUrl",
};

angular.module(moduleName, [])
.provider(
serviceName,
function(){
function randomSelector(){
var str = "";
for(var i = 0; i < 10; i++)
str += String.fromCharCode(Math.floor(Math.random() * (91-65) + 65));
return str + "_" + String(Math.random().toFixed(5)).split(".")[1];
}

this.$get = ["$templateCache",function($templateCache){
var serv = {};
//Private
function noTpl(contents){
var selector = randomSelector();
$templateCache.put(selector, contents);
return selector;
}
//Public
serv[NAMES.TEMPLATE] = function(templateUrl){

return function(tElem, tAttrs){
var defaultTpl = angular.isDefined(templateUrl) ? (angular.isFunction(templateUrl) ? templateUrl.apply(this,arguments) : templateUrl) : undefined,
elementTpl = angular.isDefined(tAttrs[NAMES.ATTR_NAME]) ? tAttrs[NAMES.ATTR_NAME] : undefined;

return elementTpl || defaultTpl || noTpl(tElem.html());
}
}
return serv;
}]
}
);
})();

一个用例

<script>
angular.module("test",["templateManager"])
.directive(
"dynTpl",
["TemplateManager",function(TemplateManager){
return {
restrict: "E",
templateUrl: TemplateManager.getTemplateUrl(
function(tElem, tAttrs){ //only for testing
if(tAttrs.testTpl === "default")
return "http://www.w3schools.com/jquery/demo_test.asp";
return undefined;
}),
}
}]
)
</script>
<body ng-app="test">
<dyn-tpl><p>Content!!</p></dyn-tpl> <!-- Should show: Content!! -->
<dyn-tpl test-tpl="default"><p>Content!!</p></dyn-tpl> <!-- Should show: This is some text from an external ASP file. -->
<dyn-tpl template-url="http://www.w3schools.com/jquery/demo_test_post.asp"><p>Content!!</p></dyn-tpl> <!-- Should show: Dear . Hope you live well in . -->
</body>

如您所见,该模块始终使用默认定义的 templateUrl、用户定义的或来自包含原始内容的缓存的 templateUrl。

我希望我能有所帮助,如果我的英语不好,我很抱歉。

关于javascript - 如何使 templateUrl 为 null 或未定义或空字符串的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26529020/

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