TemplateUrl指令:AngularJs

时间:2014-01-24 15:58:19

标签: angularjs angularjs-directive

可以将范围读入指令的templateUrl吗?

我想做这样的事情:

mDirective.directive('directive', [function () {
    return {
        restrict: 'A',
        scope: {
            types :'=types'
        },

templateUrl:'.mytemplate/'+scope.types+'.html'

1 个答案:

答案 0 :(得分:7)

指令的templateUrl中没有范围。 github上有一个功能请求:Either add scope to attributes that are passed to templateUrl function or preprocess attributes based on scope parameters

以下是两个选项(第二个是更通用的选项):

属性:范围不可用。但原始属性是。所以,如果raw属性适合你,例如它只是一个像这样的静态字符串:

<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很容易,也可以启用动画。

demo plunker显示两个选项,并使用几个按钮切换模板并查看ngInclude切换。

相关问题