指令,包装内容并保留原始元素的属性 [英] Directive, wrap content and keep attributes on original element

查看:139
本文介绍了指令,包装内容并保留原始元素的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个包含指令所应用的元素(及其子元素)的指令时遇到了一些麻烦。考虑到AngularJS中许多其他常见的东西是多么容易,我不明白为什么这个看似常见的场景应该如此困难,所以很可能我在这里遗漏了一些东西。

I have a bit of trouble creating a directive that wraps the element (and its children) that the directive is applied to. I don't get why this seemingly common scenario should be so difficult considering how easy many other commonplace things are in AngularJS, so it could very well be that I'm missing something here.

我想要做的是将一个select元素包装在div中。
我正在使用transclude保留原始的select元素及其内容,但我无法使其正常工作。

What I want to do is to wrap a select element in a div. I'm using transclude to preserve the original select element and its content but I can't get it to work correctly.

HTML如下所示:

The HTML looks like this:

<select mlb-select ng-options="opt.val as opt.text for opt in mlb" ng-model="mlbOpt"></select>

我的指令如下:

directiveModule.directive("mlbSelect", function(){
    return {
        template: '<div class="mlb-select">'
                    + '<select ng-transclude></select>'
                    + '</div>',
        transclude: 'element',
        replace: true
    }
});

生成的HTML如下所示:

The resulting HTML looks like this:

<div class="mlb-select ng-pristine ng-valid" mlb-select ng-options="opt.val as opt.text for opt in mlb" ng-model="mlbOpt">
    <select ng-transclude class="ng-scope"></select>
</div>

当然,这不是我想要的。为什么我的select元素的属性被添加到包装div而不是我用ng-transclude属性指定的元素? select元素需要保留ng-options和ng-model属性。

Of course, this is not what I want. Why are the properties of my select element added to the wrapping div and not the element I specify with the ng-transclude attribute? The select element needs to retain the ng-options and ng-model properties.

我需要做些什么来完成这个?

What do I need to do to accomplish this?

推荐答案

据我所知,唯一的方法是在包装元素中指定带有翻译的指令,例如:

As far as I know, the only way to do this is to specify the directive with transclusion in a wrapper element, e.g.:

<div mlb-select>
    <select ...></select>
</div>

当然,如果您的情况与上述情况完全相同,那么就没有必要这样做。

Of course there is no point in doing this if youe case is exactly as above.

在这个问题的上下文中的翻译大致如下:

Transclusion in the context of this question roughly works as:


  1. 被抄送的内容是具有指令的元素的内容 transclude:true ;在您的情况下,< select> 的内容为空!

  1. The transcluded content is the content of the element that has the directive with transclude: true; in your case the content of the <select>, which is empty!

被抄送的内容放置在指令模板中指定 ng-transclude 的元素内。

The transcluded content is placed inside the element that specifies ng-transclude in the template of the directive.

这篇关于指令,包装内容并保留原始元素的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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