How to set a native attribute from AngularJS directive?

前端 未结 3 1315
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 03:39

I\'d like to write HTML similar to:

test

And ha

相关标签:
3条回答
  • 2020-12-30 04:19
    <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.

    0 讨论(0)
  • 2020-12-30 04:24

    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;
      };
    });
    
    0 讨论(0)
  • 2020-12-30 04:33

    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.

    0 讨论(0)
提交回复
热议问题