Angular JS下拉列表选择"Others"选项,其他输入成为必填项



我正在尝试添加一个带有"其他"选项的下拉列表。如果用户选择"其他",其他(请注明(输入框将成为必填项。我应该如何验证此案例?现在我添加了Javassilpt代码来验证这一点。有没有办法像"请指定其他原因"那样这样做。

<form name="myForm">
    <div ng-app="myApp" ng-controller="myCtrl">
    Reason : <select ng-model="reason" ng-options="x for x in names" required></select>    <span ng-show="myForm.reason.untouched">The reason is required.</span>
<p>Others (specify): <input type="text" ng-model="others"></p>

    </div>
    </form>


    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.names = ["reason1", "reason2", "reason3","Others"];

$scope.addItem = 函数 (( {

     if ($scope.reason == "Others" && !$scope.others)
     {
         window.alert("Please specify others");
     }
     if($scope.others && $scope.reason!='Others')
     {
         window.alert("Please select reason others");
     }

    });
    </script>

Angular 有一个 ng-required 属性,允许您有条件地设置它。

<form name="myForm">
<div ng-app="myApp" ng-controller="myCtrl">
Reason : <select ng-model="reason" ng-options="x for x in names" required>
</select>    <span ng-show="myForm.reason.untouched">The reason is required.
</span>
<p>Others (specify): <input type="text" ng-model="others" ng-required="reason == 'Others'"></p>

</div>
</form>

最新更新