Tom O'Brien
Tom O'Brien

Reputation: 1831

AngularJS: How to access attributes defined inside directive from outside

I am using a directive for putting ellipsis on text overflow called angular-ellipsis. If there is enough room for the text, angular-ellipsis doesn't applythe ...'s. I need to know if the ellipsis is being applied to some text or not.

Looking into the code for the directive I can see that it has an attribute that seems to match what I am looking for - attribute.isTruncated:

compile: function(elem, attr, linker) {

    return function(scope, element, attributes) {
        /* State Variables */
        attributes.isTruncated = false;

It also seems to do something similar by setting the 'data-overflowed' attribute of the element like thus:

element.attr('data-overflowed', 'false');

Here is a link to the code for the directive, it's not too complicated or long:

https://github.com/dibari/angular-ellipsis/blob/master/src/angular-ellipsis.js

I am wondering can I access either of these attributes from my Controller, and if so how? Forgive me if this is obvious, but I completely new to directives...

Upvotes: 2

Views: 65

Answers (1)

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

Remember the "JS" in AngularJS.
If you can find your element by its id or class attribute, then you should be able query it with plain javascript, by using querySelector and getAttribute:

document.querySelector("#element-id").getAttribute('data-overflowed');

It's not a perfect solution because in some test frameworks, you are not guaranteed to have the document interface (that's why Angular has the $document wrapper), but it gets you what you need (without jQuery!). It would have been simpler if jqLite (which is used by angular.element) had enabled find by ID or classname, and not just by tag name.

Upvotes: 1

Related Questions