如何使用动态模板创建指令?
'use strict';
app.directive('ngFormField', function($compile) {
return {
transclude: true,
scope: {
label: '@'
},
template: '<label for="user_email">{{label}}</label>',
// append
replace: true,
// attribute restriction
restrict: 'E',
// linking method
link: function($scope, element, attrs) {
switch (attrs['type']) {
case "text":
// append input field to "template"
case "select":
// append select dropdown to "template"
}
}
}
});
<ng-form-field label="First Name" type="text"></ng-form-field>
这就是我现在所拥有的,它可以正确显示标签。但是,我不确定如何在模板中附加额外的 HTML。或者将 2 个模板合并为 1 个。
最佳答案
我已经使用 $templateCache 来完成类似的事情。我将几个 ng 模板放在一个 html 文件中,我使用指令的 templateUrl 引用该文件。这确保 html 可用于模板缓存。然后我可以简单地通过 id 选择来获得我想要的 ng-template。
模板.html:
<script type="text/ng-template" id=“foo”>
foo
</script>
<script type="text/ng-template" id=“bar”>
bar
</script>
指示:
myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {
var getTemplate = function(data) {
// use data to determine which template to use
var templateid = 'foo';
var template = $templateCache.get(templateid);
return template;
}
return {
templateUrl: 'views/partials/template.html',
scope: {data: '='},
restrict: 'E',
link: function(scope, element) {
var template = getTemplate(scope.data);
element.html(template);
$compile(element.contents())(scope);
}
};
}]);
关于angularjs - 如何在 AngularJS 中使用动态模板创建指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14862315/