fix(ngClass): do not break on invalid values

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
This commit is contained in:
George Kalpakas
2018-09-19 11:06:19 +03:00
parent eb0ccc625f
commit 26ddc5f830
2 changed files with 10 additions and 0 deletions
+4
View File
@@ -125,6 +125,8 @@ function classDirective(name, selector) {
}
function toClassString(classValue) {
if (!classValue) return classValue;
var classString = classValue;
if (isArray(classValue)) {
@@ -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;
+6
View File
@@ -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();