我正在制作自己的框架,我遇到了和你一样的情况。
所以我写了一个执行动态模板url的模块。如果没有定义元素或默认templateUrl,它将元素的内部内容作为字符串存储在使用随机生成的密钥命名的$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,由用户或包含原始内容的缓存中定义。
如果我的英语不好,希望能帮上忙。