Search code examples
javascriptangularjsangularjs-directiveng-class

angular ng-class with two classes, one from a variable name and one with condition


I a m a little stuck with a problem, probably some syntax I can't find on the internet.

I created an angular directive that receives a class name as a scope variable. In the tamplate I want to add the given classname and another class as conditional. something like that:

app.directive('MyDirective', function () {
    return {
        restrict: 'E',
        scope: {
            className: '=',
        },
        template: "<div ng-class="className, 'otherClass':{expression}"></div>"
    }
});

Thanks :)


Solution

  • Assuming className is a property on the scope:

    You could make use of array expression with object literal syntax itself.

     <div ... ng-class="[className, {true : 'otherClass'}[expression]]"
    

    or mix it with class

    <div ... class="{{className}}" ng-class="{'otherClass': expression}"