Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
fix(ngClass): do not break on invalid values
Browse files Browse the repository at this point in the history
Previously, when an `ngClass` expression evaluated to something that was
not a string, array or object (and was truthy), an error would be thrown
while trying to call `.split()` on a non-string value. This error was
not very helpful for the user to identify the root cause of the problem.

This commit fixes it by ensuring such values are converted to string.

Fixes #16697

Closes #16699
  • Loading branch information
gkalpak committed Sep 20, 2018
1 parent eb0ccc6 commit 26ddc5f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/ng/directive/ngClass.js
Expand Up @@ -125,6 +125,8 @@ function classDirective(name, selector) {
}

function toClassString(classValue) {
if (!classValue) return classValue;

var classString = classValue;

if (isArray(classValue)) {
Expand All @@ -133,6 +135,8 @@ function classDirective(name, selector) {
classString = Object.keys(classValue).
filter(function(key) { return classValue[key]; }).
join(' ');
} else if (!isString(classValue)) {
classString = classValue + '';
}

return classString;
Expand Down
6 changes: 6 additions & 0 deletions test/ng/directive/ngClassSpec.js
Expand Up @@ -88,6 +88,12 @@ describe('ngClass', function() {
expect(element.hasClass('AnotB')).toBeFalsy();
}));

it('should not break when passed non-string/array/object, truthy values', inject(function($rootScope, $compile) {
element = $compile('<div ng-class="42"></div>')($rootScope);
$rootScope.$digest();
expect(element.hasClass('42')).toBeTruthy();
}));

it('should support adding multiple classes via an array mixed with conditionally via a map', inject(function($rootScope, $compile) {
element = $compile('<div class="existing" ng-class="[\'A\', {\'B\': condition}]"></div>')($rootScope);
$rootScope.$digest();
Expand Down

0 comments on commit 26ddc5f

Please sign in to comment.