This question is about using a combination of bind and filters within the template of a directive. Just read through the top, it gives an understanding of what has already been done and is already working.
I am writing an application where I allow users to upload files, and the files must be of a specific MIME type.
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.
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) {
}
};
});
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>
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 "";};
});
I then re-wrote my template
as so:
template: '<input type="file" id="files" name="files[]" {{mimeType | accept}} multiple />',
As you can guess, this does not work, yet why?
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.
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.
Example:
Using your template:
Now if you change your filter return from
return 'accept="' + mimeType + '"';
toreturn mimeType;
then you should get the desired results.Fiddle