5

AngularJS - Identify all elements with a class and add an attribute without jQue...

 2 years ago
source link: https://www.codesd.com/item/angularjs-identify-all-elements-with-a-class-and-add-an-attribute-without-jquery.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

AngularJS - Identify all elements with a class and add an attribute without jQuery

advertisements

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.


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK