如何在AngularJS中使用动态模板创建指令? [英] How to create a directive with a dynamic template in AngularJS?

查看:118
本文介绍了如何在AngularJS中使用动态模板创建指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用动态模板创建指令?

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.

推荐答案

也有类似的需求. $compile完成任务. (不完全确定这是否是"THE"方法,仍然可以通过角度进行操作)

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 -我的探索测试.

要注意的一件事(以我的示例为例),我的要求之一是,一旦单击保存",模板将基于type属性进行更改,并且模板非常不同.因此,尽管如此,您获得了数据绑定,如果在那里需要新的模板,则必须重新编译.

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中使用动态模板创建指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆