Liglo App
Liglo App

Reputation: 3819

AngularJS - validation of dynamic input fields

Let's say, we have an object like:

$scope.company = { name: { de: '', en: '' } };

and an input field saying:

<input type="text" ng-model="company.name[currentLanguage]" />
<button ng-click="currentLanguage='de'">Deutsch</button>
<button ng-click="currentLanguage='en'">English</button>

If the user fills in this field, the field receives the ng-valid class. If the user then changes the language ($scope.currentLanguage in fact), the input field is correctly updated (gets empty), but it has still the ng-valid class, which is wrong. The expected behavior would be rather ng-pristine. How to update this in real time?

Would be great to know that. Cheers

PS. There isn't any more code. That's just it. PS2. It is another Problem as you suggest in the duplicate thread. I do not use ng-repeat.

Upvotes: 3

Views: 944

Answers (1)

joewright
joewright

Reputation: 325

Once an input's value is changed in any way, it doesn't reset to ng-pristine unless you force it to.

You could manage the classes in your controller like so:

$scope.currentLanguage = 'de';
$scope.company = { name: { de: '', en: '' } };

$scope.setCurrentLanguage = function(str) {
$scope.currentLanguage = str;
var input = angular.element(document).find('input')[0];
if ($scope.company.name[str] == '') {
    angular.element(input).removeClass('ng-dirty');
    angular.element(input).removeClass('ng-invalid');
    angular.element(input).addClass('ng-pristine');
} else {
    angular.element(input).removeClass('ng-pristine');
    angular.element(input).addClass('ng-dirty');
}
}

and in the html:

<input type="text" ng-model="company.name[currentLanguage]" />
<button ng-click="setCurrentLanguage('de')">Deutsch</button>
<button ng-click="setCurrentLanguage('en')">English</button>

Upvotes: 2

Related Questions