简体   繁体   中英

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.

<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. 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

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: '@' }

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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