使用angular JS动态删除验证

时间:2016-07-18 07:31:57

标签: angularjs forms validation

创建一个Web应用程序。它有一个带有5个必填输入字段的表单。它有2个按钮。一个是提交&另一个是以后保存。 当我点击提交时,表单应该验证所有必填字段&保存用户提供的输入。这对我来说很好。

当我点击“保存以供日后使用”时,只有第一个输入字段必须是必填字段。应将所有其他字段更改为可选字段。如何使用角度js实现这一点?

2 个答案:

答案 0 :(得分:1)

查看

<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>

角度控制器

$scope.isRequired = false;
$scope.stateOnChange = function () {
if ($scope.state == "TN") {
    $scope.isRequired = true;
}
else {
    $scope.isRequired = false;
}}

答案 1 :(得分:0)

ng-required

  

该指令设置元素的必需属性   ngRequired中的Angular表达式的计算结果为true。

以下示例:

&#13;
&#13;
angular
  .module('exampleApp', [])
  .controller('ExampleController', ExampleController);

function ExampleController() {
  var vm = this;
  vm.required = false;
}
&#13;
<!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>
&#13;
&#13;
&#13;