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

FIx ng-class initialization problem #2018

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/ng/directive/ngClass.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
var oldVal;

scope.$watch(attr[name], ngClassWatchAction, true);

attr.$observe('class', function(value) {
var ngClass = scope.$eval(attr[name]);
ngClassWatchAction(ngClass, ngClass);
ngClassWatchAction(ngClass);
});


Expand All @@ -26,13 +27,14 @@ function classDirective(name, selector) {
}


function ngClassWatchAction(newVal, oldVal) {
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && (newVal !== oldVal)) {
removeClass(oldVal);
}
addClass(newVal);
}
oldVal = newVal;
}


Expand Down
13 changes: 12 additions & 1 deletion test/ng/directive/ngClassSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('ngClass', function() {
expect(element.hasClass('B')).toBeFalsy();
expect(element.hasClass('AnotB')).toBeTruthy();

$rootScope.conditionB = function() { return true };
$rootScope.conditionB = function() { return true; };
$rootScope.$digest();
expect(element.hasClass('existing')).toBeTruthy();
expect(element.hasClass('A')).toBeTruthy();
Expand Down Expand Up @@ -278,4 +278,15 @@ describe('ngClass', function() {
expect(e2.hasClass('even')).toBeTruthy();
expect(e2.hasClass('odd')).toBeFalsy();
}));

it('should initialize classes correctly when $observe and $watch provide different initial values',
inject(function($rootScope, $compile) {
$rootScope.x = 'test';
element = $compile(
'<form name="f">' +
'<input name="x" ng-model="x" required ng-class="{error: f.x.$invalid}">' +
'</form>')($rootScope);
$rootScope.$digest();
expect(element.find('input').hasClass('error')).toBeFalsy();
}));
});