0

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!

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Seems like I was overthinking it. :-) Thanks for the help.
1

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);
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.