在角一个`directive`的`template`使用过滤器 [英] Using Filters on the `template` of a `directive` in angular
问题描述
这个问题是关于使用指令的模板内的绑定和过滤器的组合。刚刚从顶部看,它给了什么已经完成的理解和已经工作。 的
我写一个应用程序,我允许用户上传文件,并将这些文件必须是一个特定的MIME类型。
I am writing an application where I allow users to upload files, and the files must be of a specific MIME type.
的指令在许多地方使用,并且MIME类型需要跨这些地方发生变化。我需要动态构造模板
,以适应该指令的每个实现我的指令
的
The directive is used in many places, and the MIME type needs to change across these places. I need to dynamically construct the template
of my directive
in order to accommodate for each implementation of the directive.
我使用了模板
的指令
的结合,使之适应请求 MIME类型
从HTML:
I use binding in the template
of the directive
to make it accommodate for the requested mime-type
from the HTML:
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) {
}
};
});
正如我所说的,我说明我的 MIME类型
中的HTML执行这一指令:
As I stated, I am stating my mime-type
in the HTML implementation of this directive:
<body ng-app="app" ng-controller="appCtrl">
<file-upload mime-type="text/html"></file-upload>
</body>
这工作得很好,但恐怕在使用该指令的 没有在我的HTML声明 的 MIME类型$ C $的C>。我试图让一个
过滤器,它会消除,如果MIME类型是未定义的从模板接受属性
:
This works just fine, yet I am afraid of using this directive without declaring a mime-type in my HTML
. I tried to make a 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: '<input type="file" id="files" name="files[]" {{mimeType | accept}} multiple />',
正如您可以猜到,这是不行的,但为什么呢?
As you can guess, this does not work, yet why?
如果在 MIME类型
是未定义
或,
,过滤器应该返回,
,否则,它应该返回接受=(mime类型)
。
If the mime-type
is either undefined
or ""
, the filter should return ""
, else, it should return accept="(mimeType)"
.
这是因为如果在接受
过滤器不被认可的,为什么呢?如何让我的指令承认我的过滤器?
It's as if the accept
filter is not being recognized, why? How do I make the directive recognize my filter?
推荐答案
这是正常工作,它只是被错误地使用。
It is working properly, it's just being used incorrectly.
您正在使用前pression一个HTML标签内绑定,前pression结合只会html标签内部或外部的HTML标记的属性内工作。
You are using expression binding within an HTML tag, expression binding will only work within an attribute within the html tag or outside of an html tag.
例如:
<tag attr="{{ binding }}"></tag> <!-- Good -->
<tag>{{ binding }}</tag> <!-- Good -->
<tag {{ binding }}></tag> <!-- Bad -->
使用您的模板:
<input type="file" id="files" name="files[]" accept="{{mimeType | accept}}" multiple />
现在,如果你改变从过滤器数据回'接受='+ mime类型+'';
到返回mime类型;
,那么你应该得到想要的结果。
Now if you change your filter return from return 'accept="' + mimeType + '"';
to return mimeType;
then you should get the desired results.
这篇关于在角一个`directive`的`template`使用过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!