Robert Koritnik
Robert Koritnik

Reputation: 105019

Angular directive doesn't read attribute

I have a simple Angular directive that adds a CSS class to an element when being clicked:

.directive("addClass", function () {
    return {
        scope: {
            name: "=addClass"
        },
        link: function (scope, element, attributes) {

            element.on("click", function () {
                element.addClass(scope.name);
                console.log("Element activated");
            });

            element.on("mouseleave", function () {
                element.removeClass(scope.name);
                console.log("Element deactivated");
            });
        }
    }
});

I'm using it on my links:

<a href="" add-class="class-name">...</a>

But when I click my link my event handlers execute, although scope.name is undefined. I could read attribute value using attributes, but that beats the purpose of assigning attribute values to scope properties as described in Angular Directives API.

What am I doing wrong?

Upvotes: 2

Views: 150

Answers (2)

TruongSinh
TruongSinh

Reputation: 4856

try <a href="" add-class="'class-name'">...</a>, note the single-quoted 'class-name'

Upvotes: 0

Michael Benford
Michael Benford

Reputation: 14104

Replace =addClass with @addClass, or, in case you don't need an isolate scope, just read the class name right out of the attribute object:

element.on("click", function() {
    element.addClass(attributes.addClass);
    ...
});

The reason = doesn't work in your case is that it expects a property so a two-way binding can be established and you're providing a static string (I'm assuming you are since class-name isn't a valid property name).

Upvotes: 1

Related Questions