我想用更多模板创建指令。 并且所选模板取决于某些值(如模板类型)。 然后,如果我在html页面中调用我的指令,并更改类型模板类型,则需要更改html模板。 像这样:
<template-factory template-type={{foo}}></template-factory>
我认为我可以创建一个包含所有模板的html模板,并从 ng-if 帮助中进行选择。但我觉得它不是很好。 求助于我,为此任务选择最佳解决方案。
答案 0 :(得分:2)
有趣的是,在一个指令中,你可以传递一个函数作为你的模板,然后可以返回一个用于模板的字符串。
看看What are the benefits of a directive template function in Angularjs?,了解这是如何完成的以及利弊。
来自angular docs:
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
templateUrl: function(elem, attr){
return 'customer-'+attr.type+'.html';
}
};
});