TemplateUrl指令:AngularJs

前端之家收集整理的这篇文章主要介绍了TemplateUrl指令:AngularJs前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有可能将范围读入指令的templateUrl吗?

我想做这样的事情:

mDirective.directive('directive',[function () {
    return {
        restrict: 'A',scope: {
            types :'=types'
        },templateUrl:'.mytemplate/'+scope.types+'.html'

解决方法

范围在指令的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')},

但是如果类型可能会发生变化,这不起作用,因此可能为您提供更好的解决方案:

ngInclude您可以在ngIncludesource表达式中引用范围变量.因此,我们不使用templateURL而是使用模板,然后让ngInclude处理设置/更改模板:

template: '<div ng-include src="\'mytemplate/\'+types+\'.html\'"></div>',

您也可以手动编译并在指令中添加模板.但是使用ngInclude很容易,也可以启用动画.

demo plunker显示两个选项,并有几个按钮切换模板并查看ngInclude开关.

猜你在找的Angularjs相关文章