我当前的指令实现可能无法使用 templateUrl:
- 我将模板存储在一些变量中
- 有一个函数 getTemplate,它带有一个参数来决定通过 switch 语句返回哪个变量
- 然后像这样使用返回的变量:
我的链接器功能:
var linker = function(scope, element, attrs){
scope.$watch('networkCalled', function(value){
if(value){
// the below getTemplate returns for example: someTplVariable;
// which holds the HTML markup
element.html( getTemplate(value) );
$compile( element.contents() )(scope);
}
});
}
return {
restrict: "A",
replace: true,
link: linker,
scope: {
content: "=",
networkCalled: "="
}
我有机会在这里使用 templateUrl 功能吗?我这里有多个模板,因此我想将它们移至单独的文件中。
另一方面,如果无法使用 templateUrl,那么建议使用另一种方法,该方法仍然使我能够动态设置模板,但通过 templateUrl。
当然,如果您需要更多代码,请告诉我
最佳答案
您可以在这里做一些漂亮的事情来通过将模板设置为 ng-include 并使用 2 路绑定(bind)变量作为其 url 来获取动态模板加载:
@note 我通常会将此链接器代码放入 Controller 中以获取 url 变量上的自动摘要循环
var linker = function(scope, element, attrs){
//set default url.
scope.url = getTemplate(<default-value>);
scope.$watch('networkCalled', function(value){
if(value){
// set url to my current template. (may need $apply())
scope.url = getTemplate(value);
}
});
}
return {
restrict: "A",
replace: true,
link: linker, //dynamically include html from url var
template: "<div ng-include="url"></div>
scope: {
content: "=",
networkCalled: "="
}
关于javascript - AngularJS:当前指令实现直接使用变量中的模板,我有机会在这里使用 templateUrl 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23730760/