如何使用角度js验证选择字段(下拉列表)。当点击按钮时

时间:2016-01-21 18:57:07

标签: angularjs

如何使用角度js验证选择字段(下拉列表)。当点击按钮时 验证空值

始终需要启用

按钮。 如果下拉有选择值'作为默认选项,然后在单击按钮时提示错误

1 个答案:

答案 0 :(得分:0)

Here (Plunker)是您的功能的原始实现。

我们基本上有两个部分:

<强> index.html

<!DOCTYPE html>
  <html>
   <head>
     <link rel="stylesheet" href="style.css">
     <script src="https://code.angularjs.org/1.4.8/angular.js"></script>
     <script src="script.js"></script>
   </head>

   <body ng-app="MyApp">
     <div ng-controller = "MyAppCtrl">
       <h1>Validating input</h1>

       <form ng-submit="submit(dropSelection)">
         <label for="search.mode">Select: </label>
         <select ng-model="dropSelection" ng-options="opt for opt in options"></select>
         <button type="submit">Validate</button>
       </form>
     </div>
   </body>

 </html>

<强> app.js

var MyApp = angular.module('MyApp', []);

MyApp.controller('MyAppCtrl', function($scope){

  $scope.options = ["opt 1", "opt 2", "opt 2", "opt 3"];

  $scope.submit = function(selection){
    if(selection === undefined){
      alert('ERROR: Plese select option!');
    }else{
      alert("You've selected: " + selection );
    }

  };

 });