基于元素属性调整指令模板 [英] Adjusting directive template based on element attributes

查看:108
本文介绍了基于元素属性调整指令模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何动态地添加属性或特性在我的模板特定加价。我有我的指令是这样的:

  app.directive('myDirective',函数(){
    返回{
        限制:'A',
        模板:
            '< D​​IV><标签>标签:< /标签><输入ID =我-ID类型=文本ATTR =attrValue/>< / DIV>'
    };
});

问题1:如何将我放在 ATTR =attrValue专门就输入元素/加价?

假如我想要写:

 <我的指导性...只读>< /我-指令>

问题2:如何传递模板只读属性设置为输入元素

  app.directive('myDirective',函数(){
    返回{
        限制:'A',
        模板:
            '< D​​IV><标签>标签:< /标签><输入ID =我-ID类型=文本只读/>< / DIV>'
    };
});


解决方案

模板指令配置的属性可以是接收元素和属性作为参数和返回功能模板(看到文档)。然后,您可以构建模板时使用这些数据:

  .directive('...',函数(){
    返回{
        模板:功能(tElement,tAttrs){
            回报...<输入...'+(tAttrs.readonly'只读':'?')+'> ......;
        },
        // ...
    };
});

I would like to know how to dynamically add attribute or property to a specific mark-up in my template. I have my directive like this:

app.directive('myDirective', function() {
    return {
        restrict: 'A',
        template:
            '<div><label>Label: </label><input id="my-id" type="text" attr="attrValue"/></div>'
    };
});

Question 1: How would I place attr="attrValue" specifically on input element / mark-up?

Suppose I want to write:

<my-directive ... readonly></my-directive>

Question 2: How can I pass readonly property to the input element in the template?

app.directive('myDirective', function() {
    return {
        restrict: 'A',
        template:
            '<div><label>Label: </label><input id="my-id" type="text" readonly/></div>'
    };
});

解决方案

The template property of directive configuration can be a function that receives element and attributes as arguments and returns the template (see documentation). You can then use these data when constructing the template:

.directive('...', function () {
    return {
        template: function (tElement, tAttrs) {
            return '... <input ...' + (tAttrs.readonly ? ' readonly' : '') + '> ...';
        },
        // ...
    };
});

这篇关于基于元素属性调整指令模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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