在angular中对指令的模板使用过滤器

Using Filters on the `template` of a `directive` in angular

本文关键字:过滤器 angular 指令      更新时间:2023-09-26

这个问题是关于在指令的模板中使用绑定和过滤器的组合。只要通读顶部,它就可以理解已经完成了什么,并且已经在工作。

我正在编写一个允许用户上传文件的应用程序,文件必须是特定的MIME类型。

指令在很多地方使用,MIME类型需要在这些地方改变。我需要动态地构造directivetemplate,以适应指令的每个实现。

我在directivetemplate中使用绑定,使其适应来自HTML的请求mime-type:

app.directive("fileUpload", function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            mimeType: '@'  
        },
        template: '<input type="file" id="files" name="files[]" accept="{{mimeType}}" multiple />',
        link: function (scope) {
        }
    };
});

正如我所说的,我在这个指令的HTML实现中声明我的mime-type:

<body ng-app="app" ng-controller="appCtrl">
    <file-upload mime-type="text/html"></file-upload>
</body>

这工作得很好,但是我害怕使用这个指令而没有声明 mime-type in my HTML。我试着做一个filter which would remove the accept attribute from the template if the mime-type was undefined:

app.filter('accept', function (){
    return function(mimeType){
        if(mimeType)
        {
            if(mimeType.length)
                return 'accept="' + mimeType + '"';
            else
                return "";
        }
        else
            return "";};
});

然后我重写了我的template如下:

template: '<input type="file" id="files" name="files[]" {{mimeType | accept}} multiple />',

你可以猜到,这不起作用,但为什么呢?

如果mime-typeundefined"",过滤器应该返回"",否则,它应该返回accept="(mimeType)"

好像没有识别accept过滤器,为什么?如何使指令识别我的过滤器?

这是小提琴!

它工作正常,只是使用不当。

你在HTML标签内使用表达式绑定,表达式绑定只在HTML标签内的属性内或HTML标签外工作。

的例子:

<tag attr="{{ binding }}"></tag>  <!-- Good -->
<tag>{{ binding }}</tag>          <!-- Good -->
<tag {{ binding }}></tag>         <!--  Bad -->

使用模板:

<input type="file" id="files" name="files[]" accept="{{mimeType | accept}}" multiple />

现在,如果你改变你的过滤器返回从return 'accept="' + mimeType + '"';return mimeType;,那么你应该得到所需的结果。

小提琴