Search code examples
angularjsangularjs-directivehref

Angularjs set href does not work from directive


So I wrote a directive that will be applied to link tags like this: <a href="..." replace-link"></a>. What the directive does is check some stuff and then modify/replace/remove the href. It also does some additional stuff, so I do not and can not use ng-href for my purpose.

The directive contains the following code:

myApp.directive('replaceLink', function () {
return {
    link: function (scope, element, attrs) {
        attrs.$set('href', attrs.href + 'REPLACED!');
    }
};
});

but does not seem to work. When changing it to something like

attrs.$set('newhref', attrs.href + 'REPLACED!');

and inspecting the source later, I can see that it worked and the new attribute was set. Why can I not set the "href" attribute?


Solution

  • Turns out the issue was that the original html-link to begin with was bound to an angular variable:

    <a href="some-link/{{variable}}" replace-link>
    

    applying the directive and binding to the variable (and thus changing the link) are now competing / race conditions.

    My solution was to use a different attribute to bind to and have the directive copy from this to the href attribute on demand (only when the link should not be 'unset').

    Kinda hard to explain, so I created a jsfiddle to illustrate this a bit more: http://jsfiddle.net/akg7yd4f/3/