0

I have to identify all the elements having class in-brackets and add an attribute href="#" to them. I have to do this without jQuery.

This is my code example now:

<a class="in-brackets">Banana</a>
<a class="in-brackets">Apple</a>

In my Controller:

document.getElementsByClassName("in-brackets").setAttribute("href", "#");

But nothing happens. The element doesn't have the attribute.

  • 2
    Have you read [How do I "think in AngularJS" if I have a jQuery background?](http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background?rq=1) – JoseM Apr 07 '14 at 12:51
  • @JoseM excellent resource! The point of this link is to think about why you're trying to set href to #. My guess based upon my experiences is that the links aren't showing as links, which I've solved via CSS: a{cursor: pointer;} – Brocco Apr 07 '14 at 13:03

3 Answers3

2

The "Angular way" is to only do DOM manipulation inside a directive.
You can build a custom directive for that:

.directive('inBrackets', function () {
    return {
        restrict: 'C',
        link: function postLink(scope, elem, attrs) {
            attrs.$set('href', '#');
        }
    };
});

Read more about custom directives and the various properties of the "Directive Definition Object" here.

gkalpak
  • 47,844
  • 8
  • 105
  • 118
1

You'll have to iterate the elements:

var elems = document.getElementsByClassName("in-brackets");

for (var i = 0; i < elems.length; i++) {
    elems[i].setAttribute("href", "#");
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • While correct in general, direct DOM manipulation is against the Angular philosophy (and highly discouraged in an Angular app). – gkalpak Apr 07 '14 at 12:59
0

Have you tried jqLite bundled with AngularJS? It works similarly to jQuery (though only the most used features are supported); you might feel comfortable with it if you have a jQuery background.

angular.element(document.getElementsByClassName("in-brackets")).attr("href", "#");
mingos
  • 23,778
  • 12
  • 70
  • 107