AngularJS下拉列表验证

时间:2017-12-01 18:02:17

标签: angularjs

美好的一天,

我试图在AngularJS中创建一个简单的下拉列表。下拉列表正在填充,但我想要的是:

如果用户提交了该按钮并且下拉列表未选择 ,那么我希望在下拉列表正下方显示一条错误消息。我非常确定我正确使用ng-show,而console.log告诉我控制器中没有选择下拉列表,但我看不到我的文字。< / p>

这是我的HTML:

sample.controller('SampleController', ['$scope', '$location',
    function ($scope, $location) {

        $scope.services = [
            { ServiceID: 1, ServiceName: 'Service1' },
            { ServiceID: 2, ServiceName: 'Service2' },
            { ServiceID: 3, ServiceName: 'Service3' }
        ];

        $scope.serviceNotSelected = false;

        $scope.submitForm = function(isValid) {

            if ($scope.ServiceID === "" || $scope.ServiceID === undefined) {
                console.log('Not Selected:  ' + $scope.ServiceID);
                $scope.serviceNotSelected = true;       
            } else {
                console.log('Selected: ' + $scope.ServiceID);
            }

            console.log('isValid is:  ' + isValid);


            // check to make sure the form is completely valid
            if (isValid) {
                alert('our form is amazing');
            }
        };

    }
]);

这是我的控制者:

{{1}}

我的演出不起作用。谁能告诉我为什么?

TIA,

COSON

2 个答案:

答案 0 :(得分:0)

修改您的表单,使其仅在有效时提交:

<form role="form" name="myForm" ng-submit="myForm.$valid && submitForm()">

删除无用的notSelected内容。 myForm。$ submit只有在您尝试提交表单时才会成立(即使由于验证而失败)

<div class="red" ng-show="myForm.service_id.$invalid && myForm.$submitted">You must select a service.</div>

从提交方法中删除这些内容:

$scope.submitForm = function() {
  //if you are here, your form is valid.
};

这应该有用。

答案 1 :(得分:0)

我认为这是因为你在select中添加了你的错误div。在select之外添加div应解决问题

    <select name="service_id" class="form-control"
            ng-model="ServiceID" 
            ng-options="service.ServiceID as service.ServiceName for service in services"
            required> 
        <option value="">Select Service</option>                              
    </select> 

   <div class="red" ng-show="myForm.service_id.$invalid && serviceNotSelected">You must select a service.</div>