是否可以将作用域读入指令的templateUrl中?
我想做类似于这样的事情:
mDirective.directive('directive', [function () {
return {
restrict: 'A',
scope: {
types :'=types'
},
templateUrl:'.mytemplate/'+scope.types+'.html'
是否可以将作用域读入指令的templateUrl中?
我想做类似于这样的事情:
mDirective.directive('directive', [function () {
return {
restrict: 'A',
scope: {
types :'=types'
},
templateUrl:'.mytemplate/'+scope.types+'.html'
指令的templateUrl中不可用scope。 在github上有一个功能请求:要么将作为参数传递给templateUrl函数的属性添加到scope中,要么基于scope参数预处理属性。
以下是两个选项(第二个选项更加通用):
属性:Scope不可用。 但原始属性是可用的。 因此,如果原始属性适用于您,例如它只是一个静态字符串,如下所示:
<div directive types="test1"></div>
然后,我们可以将一个函数传递到 templateUrl
中。第二个参数将是属性,因此您可以像这样使用该字符串构造模板URL:
templateUrl: function(elem, attrs){ return ('mytemplate/'+attrs.types+'.html')},
但是如果 types
可能会改变,那么更好的解决方案可能是:
ngInclude 您可以在 ngInclude
源表达式中引用作用域变量。 因此,我们不使用 templateURL
而使用 template
,然后让 ngInclude
处理设置/更改模板:
template: '<div ng-include src="\'mytemplate/\'+types+\'.html\'"></div>',
ngInclude
既简单又能启用动画效果。
演示 plunker展示了两种选项,并提供了几个按钮来切换模板并查看ngInclude
的切换。