Search code examples
javascriptangularjsng-class

Angular evaluate expression when set as a property


Say for instance you have the following:

    $scope.element =
            {
                html: '<a type="button" class="btn btn-xs btn-rounded m-r-sm"><i class="icon icon-user-unfollow"></i></a>',
                classExpression : " {{inactive == 'true' ? 'btn-success': 'btn-danger'}}",
            }

As you can see we have a veriable called classExpression which is the expression i wish to append to the element

 <span  ng-bind-html="element.html | trust" class="{{element.classExpression}}">Text in between<span>

However it doesnt evaluate it.

So my question how is this possible (if it is even possible)

fiddle

Updated my fiddle (it wasnt working)


Solution

  • I'd say refactor your object to have following structure. I don't really encourage you to put expressions into string.

    HTML

    <span ng-bind-html="element.html" ng-class="element.classExpression[element.inactive]">
        Text in between
    </span>
    

    Code

    $scope.element = {
        html: '<a type="button" class="btn btn-xs btn-rounded m-r-sm"><i class="icon icon-user-unfollow"></i></a>',
        classExpression: {
          'true': 'btn-success',
          'false': 'btn-danger'
        },
        inactive: 'true'
    };
    

    Forked Fiddle