如何从 AngularJS 指令设置本机属性? [英] How to set a native attribute from AngularJS directive?

查看:26
本文介绍了如何从 AngularJS 指令设置本机属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写类似于以下内容的 HTML:

I'd like to write HTML similar to:

<a href="sharedasset: img.png">test</a>
<img src="sharedasset: img.png"/>

并且有一个名为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?

更新

自从我最初发布这篇文章以来,Angular 已经有了一些改进,因此我想我会分享我现在所做的事情.在 HTML 中,我使用 Guido Bouman 的答案,即创建过滤器,现在使用 Angular 的 bind once 功能,这使其成为我认为的最佳选择.

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.

虽然在 JS 代码中,而不是在任何地方注入 $filter 和我的 globalVars 常量,现在我只是在任何前面加上 static 这个词托管在静态内容服务器上的资产的路径,例如 {templateUrl: "static/someTemplate.html"} 然后使用 Angular HTTP Interceptor 查找任何以static"开头的路径和将其替换为静态服务器的域.很简单.

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.

推荐答案

<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);
            }
        },
    }
});

我不知道您从哪里获得 fullPathUrl,所以我在链接函数中对其进行了硬编码.

I don't know where you are getting fullPathUrl from, so I hardcoded it in the link function.

这篇关于如何从 AngularJS 指令设置本机属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆