简体   繁体   English

AngularJS-动态模板URL

[英]Angularjs - dynamic template URL

I have a directive which I would like to be able to load a different template on some logic. 我有一个指令,我希望能够在某些逻辑上加载其他模板。

In the example below, the 'type' is a variable on the scope which I would like to pass to the directive to build the URL for the directive's template. 在下面的示例中,“ type”是作用域上的变量,我希望将其传递给指令以构建指令模板的URL。

<direct type="{{type}}"></direct>

var direct = function () {
  return {
  restrict: 'E',
  templateUrl: function(tElement, tAttrs) {
    console.log(type);
    return 'resources/' + tAttrs.type + '.html';
  }
 };
};

The type is not being evaluated but instead the actual string 'type' is being passed in the tAttrs. 不评估类型,而是在tAttrs中传递实际的字符串“ type”。 Do you know what I might be missing out? 你知道我可能会错过什么吗?

You have to do this via isolated scope on your direct directive. 您必须通过直接指令上的隔离范围来执行此操作。

I have made an example for you here: http://jsbin.com/lagez/1/edit 我在这里为您提供了一个示例: http : //jsbin.com/lagez/1/edit

You can see in the example link, that you have to specify attributes that you would like to read inside your directive scope inside the scope: { attributeName: '@' } 您可以在示例链接中看到,必须在范围内的指令范围内指定要读取的属性:{attributeName:'@'}

The attribute name syntax inside scope: {} should be camel case with first letter small. 作用域{}中的属性名称语法应为驼峰式,且首字母较小。 eg typeName, and you specify the attribute-name inside the directive like 例如typeName,然后在指令中指定属性名称,例如

您遇到的问题是,在评估templateUrl时,没有将该值绑定到的范围,因此它返回属性的实际字符串内容-而不是您期望的插值值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM