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

Commit 56bcc04

Browse files
gronerIgorMinar
authored andcommitted
feat(ng:class): support using map of classnames and conditions
enables <div ng:class="{'hide': !visible, 'warning': isAlert()}"...
1 parent b2052d0 commit 56bcc04

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/directives.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,12 @@ function ngClass(selector) {
527527
scope.$watch(expression, function(newVal, oldVal) {
528528
if (selector(scope.$index)) {
529529
if (oldVal && (newVal !== oldVal)) {
530+
if (isObject(oldVal) && !isArray(oldVal))
531+
oldVal = map(oldVal, function(v, k) { if (v) return k });
530532
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
531533
}
534+
if (isObject(newVal) && !isArray(newVal))
535+
newVal = map(newVal, function(v, k) { if (v) return k });
532536
if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal);
533537
}
534538
});
@@ -551,7 +555,8 @@ function ngClass(selector) {
551555
*
552556
* @element ANY
553557
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
554-
* of the evaluation can be a string representing space delimited class names or an array.
558+
* of the evaluation can be a string representing space delimited class
559+
* names, an array, or a map of class names to boolean values.
555560
*
556561
* @example
557562
<doc:example>

test/directivesSpec.js

+22
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,28 @@ describe("directive", function() {
200200
}));
201201

202202

203+
it('should support adding multiple classes conditionally via a map of class names to boolean' +
204+
'expressions', inject(function($rootScope, $compile) {
205+
var element = $compile(
206+
'<div class="existing" ' +
207+
'ng:class="{A: conditionA, B: conditionB(), AnotB: conditionA&&!conditionB}">' +
208+
'</div>')($rootScope);
209+
$rootScope.conditionA = true;
210+
$rootScope.$digest();
211+
expect(element.hasClass('existing')).toBeTruthy();
212+
expect(element.hasClass('A')).toBeTruthy();
213+
expect(element.hasClass('B')).toBeFalsy();
214+
expect(element.hasClass('AnotB')).toBeTruthy();
215+
216+
$rootScope.conditionB = function() { return true };
217+
$rootScope.$digest();
218+
expect(element.hasClass('existing')).toBeTruthy();
219+
expect(element.hasClass('A')).toBeTruthy();
220+
expect(element.hasClass('B')).toBeTruthy();
221+
expect(element.hasClass('AnotB')).toBeFalsy();
222+
}));
223+
224+
203225
it('should support adding multiple classes via a space delimited string', inject(function($rootScope, $compile) {
204226
var element = $compile('<div class="existing" ng:class="\'A B\'"></div>')($rootScope);
205227
$rootScope.$digest();

0 commit comments

Comments
 (0)