diff --git a/src/components/input/input.js b/src/components/input/input.js index df172a6517a..1996f6bb16b 100644 --- a/src/components/input/input.js +++ b/src/components/input/input.js @@ -620,12 +620,6 @@ function mdMaxlengthDirective($animate, $mdUtil) { // over the maxlength still counts as invalid. attr.$set('ngTrim', 'false'); - ngModelCtrl.$formatters.push(renderCharCount); - ngModelCtrl.$viewChangeListeners.push(renderCharCount); - element.on('input keydown keyup', function() { - renderCharCount(); //make sure it's called with no args - }); - scope.$watch(attr.mdMaxlength, function(value) { maxlength = value; if (angular.isNumber(value) && value > 0) { @@ -642,6 +636,11 @@ function mdMaxlengthDirective($animate, $mdUtil) { if (!angular.isNumber(maxlength) || maxlength < 0) { return true; } + + // We always update the char count, when the modelValue has changed. + // Using the $validators for triggering the update works very well. + renderCharCount(); + return ( modelValue || element.val() || viewValue || '' ).length <= maxlength; }; }); diff --git a/src/components/input/input.spec.js b/src/components/input/input.spec.js index 55c2f14b270..88a13418c7e 100644 --- a/src/components/input/input.spec.js +++ b/src/components/input/input.spec.js @@ -294,6 +294,33 @@ describe('md-input-container directive', function() { expect(getCharCounter(element).text()).toBe('3/6'); }); + it('should update correctly the counter, when deleting the model value', function() { + var el = $compile( + '
' + )(pageScope); + + pageScope.$apply(); + + // Flush any pending $mdUtil.nextTick calls + $timeout.flush(); + + expect(pageScope.form.foo.$error['md-maxlength']).toBeFalsy(); + expect(getCharCounter(el).text()).toBe('0 / 5'); + + pageScope.$apply('foo = "abcdef"'); + expect(pageScope.form.foo.$error['md-maxlength']).toBe(true); + expect(getCharCounter(el).text()).toBe('6 / 5'); + + + pageScope.$apply('foo = ""'); + expect(pageScope.form.foo.$error['md-maxlength']).toBeFalsy(); + expect(getCharCounter(el).text()).toBe('0 / 5'); + }); + it('should add and remove maxlength element & error with expression', function() { var el = $compile('