Marc Rasmussen Marc Rasmussen - 9 months ago 36
AngularJS Question

angularjs ng-class on html from object property

I am creating a directive where you are able to pass different type of html elements and inject them into a table.

However sometimes my users might need to add some kind of expression to the ng-class directive

check for instance the following:

$scope.element =
html: '<button type="button" ng-class="element.classExpression">My button</button>',
classExpression : "element.classExpressionDefault ? 'btn-success': 'btn-danger'",
classExpressionDefault: $scope.inactive,


<span ng-bind-html-unsafe="element.html"> </span>

Please note the above code does not work!

The problem with the above code is that the expression is not being evaluated and therefor it goes lost.

So my question is how may i add it and is it possible?


As Brant already hints at in his answer you can compile the html of the $scope.element from within your directive to evaluate angular expressions.

For that purpose you need to inject the $compile service and call it with the directives $scope on the element.html:

angular.module('ui.directives', []).directive('exampleDirective', ['$compile',
function ($compile) {
    return {
        restrict: 'E',
        scope: { element: '=' },
        template: '<span ng-bind-html-unsafe="element.html"></span>',
        link: function ($scope, element, attrs, controller) {
            $scope.element = {
                html: 'I am an <code>HTML</code>string with <p style="color: {{element.color}}">color</p>',
                color: 'red'
            $scope.element.html = $compile($scope.element.html)($scope);

Of course you can then pass in the element via the template that uses the directive and have it defined the parent controller:

$scope.element = {
            html: 'I am an <code>HTML</code>string with <p style="color: {{element.color}}">color</p>',
            color: 'red'


<example-directive element="element"></example-directive>