Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a native attribute from AngularJS directive?

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.

like image 813
adam0101 Avatar asked Aug 13 '13 20:08

adam0101


People also ask

Which directive do we use to inform AngularJS about the parts controlled by it?

The ngRef attribute tells AngularJS to assign the controller of a component (or a directive) to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM element to the scope. The ngRepeat directive instantiates a template once per item from a collection.

What is custom directive in AngularJS?

Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.

Which directive is used to specify a controller in HTML?

The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element.


1 Answers

<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.

like image 75
Mark Rajcok Avatar answered Sep 20 '22 11:09

Mark Rajcok