From 1a677469a96257426ed820f410f613df762917a5 Mon Sep 17 00:00:00 2001 From: George Kalpakas Date: Wed, 19 Sep 2018 11:06:19 +0300 Subject: [PATCH] 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 --- src/ng/directive/ngClass.js | 4 ++++ test/ng/directive/ngClassSpec.js | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/src/ng/directive/ngClass.js b/src/ng/directive/ngClass.js index 664e4810ce2..fc7b6db2c03 100644 --- a/src/ng/directive/ngClass.js +++ b/src/ng/directive/ngClass.js @@ -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; diff --git a/test/ng/directive/ngClassSpec.js b/test/ng/directive/ngClassSpec.js index 0180d67a6aa..74500505fd8 100644 --- a/test/ng/directive/ngClassSpec.js +++ b/test/ng/directive/ngClassSpec.js @@ -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('
')($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('
')($rootScope); $rootScope.$digest();