Reputation: 13
Am creating a web application. It has a form with 5 mandatory input fields.It has 2 buttons. One is submit & another one is save for later. When I click on submit, the form should validate all the mandatory fields & save the input given by the user. This is working fine for me.
When I click on "save for later", only the first input field should be mandatory. All other fields should be changed as optional. How to achieve this using angular js?
Upvotes: 0
Views: 2031
Reputation: 728
View
<form name="Form" ng-controller="testController">
<input name="input" type="text" id="txtName" ng-model="Name" class="form-control" required>
<select ng-model="state" ng-options="s for s in stateList" id="state" ng-change="stateOnChange()" class="form-control"></select>
<input name="input" type="text" id="txtstate" ng-model="pincode" class="form-control" required>
<input name="input" type="text" id="txtplace" ng-model="place" class="form-control" ng-required={{isRequired}}>
<button type="submit" class="btn btn-success" ng-submit="saveAction();">Save</button>
Angular Controller
$scope.isRequired = false;
$scope.stateOnChange = function () {
if ($scope.state == "TN") {
$scope.isRequired = true;
}
else {
$scope.isRequired = false;
}}
Upvotes: 1
Reputation: 1755
See ng-required.
The directive sets the required attribute on the element if the Angular expression inside ngRequired evaluates to true.
Example below:
angular
.module('exampleApp', [])
.controller('ExampleController', ExampleController);
function ExampleController() {
var vm = this;
vm.required = false;
}
<!DOCTYPE html>
<html ng-app='exampleApp'>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
</head>
<body ng-controller="ExampleController as vm">
<form name="vm.form">
<label for="required">Toggle required:</label>
<input type="checkbox" ng-model="vm.required" id="required" />
<br>
<label for="input">This input must be filled if `required` is true:</label>
<input type="text" ng-model="model" id="input" name="input" ng-required="vm.required" />
<br>
<p>required status: {{vm.required}}</p>
<p>form error: {{vm.form.input.$error}}</p>
</form>
</body>
</html>
Upvotes: 0