我正在使用一个指令,该指令将根据传入其中的范围值动态加载模板。
我在我的指令上使用ng-repeat,并使用迭代项作为属性属性:
<my-form-field ng-repeat="field in customFields" field="field">
在我的指令中,我有以下代码来设置正在使用的模板。
(function() {
'use strict';
angular
.module('app')
.directive('myFormField', myFormField);
function myFormField() {
var directive = {
restrict: 'E',
scope: {
field: '='
},
link: function(scope){
scope.getContentUrl = function() {
return 'app/modules/form_components/form_field/' + scope.field.type + '-template.html';
}
},
template: '<div ng-include="getContentUrl()"></div>'
};
return directive;
}
})();
虽然上述作品(我从其他帖子中找到),我想知道是否有更好的方法。
例如,我已经看到了在templateUrl配置选项上调用函数的示例,然后在该函数中访问传入的范围属性。当我尝试这种方式时,我的字段属性是文字“字段”字符串值(它们是我的customFields数组中的对象),所以我认为此时范围变量尚未被评估。
使用我现在使用的当前解决方案,因为我使用的是ng-include,所以我的所有模板都包含在一个额外的div中,所以我只是想让渲染的标记更简洁。
任何建议\建议表示赞赏。 感谢