问题
I'd like to write HTML similar to:
<a href="sharedasset: img.png">test</a>
<img src="sharedasset: img.png"/>
And have a directive called "sharedasset" that gets the full path to img.png
and sets the value of the attribute without the directive having any knowledge of what the attribute name is ahead of time. Is this possible?
Update
Since I originally posted this there have been some improvements to Angular and I thought I'd share what I do now as a result. In the HTML I use Guido Bouman's answer which is to create a filter and, now with Angular's bind once feature, this makes it the best option in my opinion.
In the JS code though, instead of injecting $filter
and my globalVars
constant everywhere, now I just prepend the word static
to any path of an asset that is hosted on the static content server like {templateUrl: "static/someTemplate.html"}
and then use an Angular HTTP Interceptor to look for any path that begins with "static" and replace it with the domain for the static server. Very simple.
回答1:
<a full-path="img.png">test</a>
<img full-path="img.png">
app.directive('fullPath', function() {
return {
link: function(scope, element, attrs) {
var fullPathUrl = "http://.../";
if(element[0].tagName === "A") {
attrs.$set('href',fullPathUrl + attrs.fullPath);
} else {
attrs.$set('src',fullPathUrl + attrs.fullPath);
}
},
}
});
I don't know where you are getting fullPathUrl
from, so I hardcoded it in the link function.
回答2:
I didn't want the directive to care what the attribute name was, so this is what I ended up doing:
<a shared-asset="images/img.png" attr="href">test</a>
<img shared-asset="images/img.png" />
app.directive('sharedAsset', function (globalVars) {
return {
restrict: "A",
scope: {
attr: "@attr"
},
link: function (scope, element, attrs) {
var fullPath = globalVars.staticWebsite + "/app/styles/main/" + attrs.sharedAsset + "?build=" + globalVars.buildNumber;
attrs.$set(scope.attr || "src", fullPath);
}
};
});
Update: I changed it to default to the "src" attribute since images will be the most common scenario.
回答3:
A custom filter is much more suited for this case than a directive:
<a href="{{'images/img.png' | fullPath}}">test</a>
<img src="{{'images/img.png' | fullPath}}" />
The filter: (Assuming you have a global filters
module)
angular.module('filters').filter('fullPath', function(globalVars) {
return function(url) {
return globalVars.staticWebsite + "/app/styles/main/" + url + "?build=" + globalVars.buildNumber;
};
});
来源:https://stackoverflow.com/questions/18218956/how-to-set-a-native-attribute-from-angularjs-directive