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

查看:24
本文介绍了如何在 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"方式,仍在通过 angular 工作)

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天全站免登陆