问题描述
我怎样才能创建一个动态模板指令?
How can I create a directive with a dynamic template?
'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。
This is what I have right now, and it is displaying the label correctly. However, I'm not sure on how to append additional HTML to the template. Or combining 2 templates into 1.
推荐答案
也有类似的需求。 $编译
做这项工作。 (不能完全肯定,如果这是的方式做到这一点,还是通过角工作我的方式)
Had a similar need. $compile
does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)
- 我的探索试验
http://jsbin.com/ebuhuv/7/edit - my exploration test.
有一点要注意(按我的例子),我的要求之一是,模板会改变基于一个键入
属性,一旦你点击保存,和模板,非常不一样。所以,虽然,你得到的数据绑定,如果需要有一个新的模板,你将不得不重新编译。
One thing to note (per my example), one of my requirements was that the template would change based on a type
attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.
这篇关于AngularJS - 指令模板动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!