Reputation: 1523
I'm trying to get some form inputs to validate if/when their model updates. Currently the only way to remove the pristine class is to manually type in the input box.
Fiddle: http://jsfiddle.net/TgR7A/ In the fiddle if you click 'toggle' the 2 inputs (one is always hidden) populate with content via their models but the form input stays pristine. I know this is AngularJS's way of handling form inputs but I'm hoping for a workaround (A.K.A hack!) that allows for the inputs to validate.
HTML:
<div ng-app>
<div ng-controller="toggleCtrl">
<h1>{{ title }}</h1>
<form novalidate class="css-form" name="swtichForm">
<label>Input</label>
<input type="text" name="one" class="one" ng-show="input_show=='one'" ng-model="one" required />
<input type="text" name="two" class="two" ng-show="input_show=='two'" ng-model="two" required />
<p ng-click="toggle()">Toggle</p>
</form>
</div>
CSS:
.one {
border-color: blue;
}
.two {
border-color: yellow;
}
.css-form input.ng-invalid {
background-color: #FA787E;
}
.css-form input.ng-valid {
background-color: #78FA89;
}
.css-form input.ng-pristine {
background: #fff;
}
JS:
function toggleCtrl($scope) {
$scope.title = "Input toggle";
$scope.input_show = "one";
$scope.toggle = function () {
$scope.one = 'hello';
$scope.two = 'world';
$scope.input_show = ($scope.input_show == 'one' ? 'two' : 'one');
}
}
Upvotes: 3
Views: 2300
Reputation: 20421
You will find a good explanation here on Stack Overflow.
Unfortunately, althought there is a $setPristine()
function, there is no $setDirty()
one. As stevuu suggest, the least ugly way to solve your problem is to call $setViewValue()
with the new value, and then force the view to update with $render()
:
$scope.toggle = function () {
$scope.switchForm.one.$setViewValue('hello');
$scope.switchForm.two.$setViewValue('world');
$scope.switchForm.one.$render();
$scope.switchForm.two.$render();
$scope.input_show = ($scope.input_show == 'one' ? 'two' : 'one');
}
Upvotes: 2