Search code examples
javascriptangularjsangularjs-directiveng-class

AngularJs Directives: nested ng-class is failing


I'm facing a strange issue with AngularJs Directive when I need to have nested ng-class. Here is a JSFiddle that shows the problem with an hypothetical situation.

HTML

<div in-directive ng-class="{ 'testing1': 1 == 1 }"></div>

Javascript

var myApp = angular.module('myApp', []);

myApp.directive('inDirective', function () {
    return {
        restrict: 'A',
        replace: true,
        template: '<div ng-class="{ \'testing\': 1 == 1 }">Hi</div>'
    };
});

AngularJS Error

Syntax Error: Token '{' is an unexpected token at column 25 of the expression [{ 'testing11': 1 == 1 } { 'testing': 1 == 1 }] starting at [{ 'testing': 1 == 1 }].

[{ 'testing11': 1 == 1 } { 'testing': 1 == 1 }]

This is an invalid JSON. Am I doing something wrong here? Currently, the work-around that I did was to move the ng-class to a upper div element. But this is clearly not desired.


Solution

  • This similar issue has already been reported here #8159 Directive with 'replace: true' and template.

    And AngularJS team has decided not to support a complex attribute merging when using a directive with template/templateUrl and replace flag set to true.

    And this issue is one of the reason why they are deprecating the replace flag of directives.

    You can also see a long discussion here eec6394: deprecate replace directives