单击按钮时$ error.required显示为false

时间:2016-05-06 10:29:34

标签: angularjs

我在下拉列表中设置了属性ng-required="true"

点击按钮我想验证下拉列表。但最初$ error.required显示的false应为true

但是,如果我更改dropdownlist $ error.require的值完全正常。

 <select id="ddlsolution" name="ddlsolution" ng-model="Detail.CCESolution" ng-options="solutionName.id as solutionName.type for solutionName in solutionNames" ng-required="true">
                                            <option value="">-- Select Solution --</option>
                                        </select>

<button type="submit" class="gradient-button1" style="float: right; margin-left: 8px; margin-right: 10px;" ng-click="validateFields()">Submit</button>


function validateFields() {
            if ($scope.registrationForm.ddlsolution.$error.required) {
                alert("error");
            }
            else {
                alert("no error");
            }
        }

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

&#13;
&#13;
var app = angular.module("Demo", []);
app.controller("AppController", function($scope) {
  $scope.validateFields = function(valid) {
    if (valid) {
      alert("valid")
    } else {
      alert("invalid")
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <select id="ddlsolution" name="ddlsolution" ng-model="selectedDdl" required>
        <option value="">-- Select Solution --</option>
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
      </select>

      <button type="submit" class="gradient-button1" ng-click="validateFields(regForm.$valid)">Submit</button>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

http://jsfiddle.net/03L3faq5/9/

希望它会有所帮助。谢谢。

答案 1 :(得分:0)

您可以使用$invalid,如下所示

&#13;
&#13;
var app = angular.module("Demo", []);

 app.controller("AppController", function($scope) {
   
   $scope.validateFields = function() {
     
   if($scope.myForm.ddlsolution.$invalid){
      alert("error");  
   }else{
    alert("no error");  
   }
     
    }
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="myForm">
      <select id="ddlsolution" name="ddlsolution" ng-model="Detail.CCESolution" required>
        <option >-- Select Solution --</option>
        <option value="value1">Value</option>
        <option value="value2">Value</option>
      </select>

      <button type="submit" class="gradient-button1" style="float: right; margin-left: 8px; margin-right: 10px;" ng-click="validateFields()">Submit</button>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;