如何将元素的属性添加到 angular 指令 [英] How to add attributes of element to angular directive

查看:28
本文介绍了如何将元素的属性添加到 angular 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 的新手.我想编写一个指令,其中包含我在 html 中使用时添加的所有属性.例如:

I'm new to angular. I want to write a directive which has all the attributes that I added to it when using in html. For example:

这是我的指令

'use strict';
app.directive('province', function($compile) {
    return {
        restrict: 'E',
        link: function (scope, element, attrs, controller) {
            var markup = "<select></select>";
            var elem = angular.element(element);
            elem.replaceWith($compile(markup)(scope));
         }
    };

})

HTML:

<province class="form-control" data-target"elemntId"></province>

我希望我的

output that I want: <select class="form-control" data-target="elementId"></select>

我使用了 angular.element(element).attr(attr);,但它不起作用;

I used angular.element(element).attr(attr);, but it does not worked;

提前感谢任何帮助.

编辑

我希望将链接函数 attrs 中存在的所有属性添加到 markup.

I want all the attributes that exist in attrs of link function to be added to markup.

推荐答案

根据您的需要,您不需要自己编译.您可以使用模板并替换.

Depending on your needs, you don't need to compile yourself. You can use template and replace instead.

app.directive('province', function() {
    return {
        restrict: 'E',
        template: '<select></select>',
        replace: true,
        link: function (scope, element, attrs) {
        }
    };
});

参见 plnkr

这篇关于如何将元素的属性添加到 angular 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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