将模板内的局部范围变量作为变量而不是字符串访问

时间:2015-07-21 19:16:24

标签: angularjs angularjs-directive

我正在创建一个指令,其中我有一个带有变量type的范围(本地),并且我应该返回相应的模板。 chooseTemplateByType会根据type返回一个包含相应模板的字符串,例如text_field

template:
  chooseTemplateByType(type)

问题是如何访问我的本地范围的变量类型,以便我可以将值传递给我的函数chooseTemplateByType

1 个答案:

答案 0 :(得分:3)

实现此目的的最佳方法是通过属性将type变量传递给您的指令。

HTML

<my-directive type="foo"></my-directive>

JS

myApp.directive('myDirective', function() {
  return {
    template: function(elem, attr){
      return "<h1>" + attr.type + "</h1>"; // will output <h1>foo</h1>
    }
  };
});

OR

myApp.directive('myDirective', function() {
  return {
    templateUrl: function(elem, attr){
      return attr.type + '.html'; // will load foo.html
    }
  };
});