nikk wong
nikk wong

Reputation: 8670

AngularJS Updating attribute in directive linking function dynamically

I have a directive that receives a string, which I would like the directive to then modify and add as an attribute's property.

HTML

<div directive ng-class="" otherAttribute="hello"></div>

JS

.directive('directive', function () {

return {

    link: function (scope, elem, attrs) {

            var classList = "{active: attrs.otherAttribute == 'hello'}";

            attrs.ngClass = classList;

            console.log(attrs);

        }

    }

})

This does seem to add the properties to the class property of the attrs object:

console.log(attrs);

$$observers: Object
$attr: Object
ngClass: "{active: attrs.otherAttribute == 'hello'}"
otherAttribute: "hello"
__proto__: Object

But the DOM is not updated. I've tried $compile, but that does not update the class attribute on the DOM either.

What am I missing? Many thanks!

Upvotes: 0

Views: 458

Answers (2)

Kirill Slatin
Kirill Slatin

Reputation: 6143

You can use interpolation and reference directive scope

 <div directive class="class1 {{classList}}" otherAttribute="hello"></div>

link: function (scope, elem, attrs) {
        scope.classList = "class2";
}

Pay attention that in your code there is an error, you reference an undefined scope.classList with an += operator, resulting in undefinedclass1 class2 literal. I suppose this might be a typo in example...

Upvotes: 1

Ernesto Rendon
Ernesto Rendon

Reputation: 312

You can use the directive element to modify a css class.

Working example of your code: http://jsfiddle.net/egrendon/vvnu5yLx/1/

app.directive('directive', function () {
    return {
        link: function (scope, element, attrs) {
            scope.classList += "class1 class2";
            element.addClass(scope.classList);
            console.log(attrs);
        }
    }
});

Upvotes: 1

Related Questions