简体   繁体   English

在Select上进行ng模式的较小解决方案

[英]Smaller Work around for ng-pattern on Select

I am working on an angular app and I needed to put a pattern validation on a select element. 我正在开发一个有角度的应用程序,需要在选择元素上进行模式验证。 Just using ng-pattern on select didn't work. 仅在选择上使用ng-pattern无效。 So I created a hidden input with same model with ng-pattern on the hidden input, that didn't work either. 因此,我在隐藏的输入上创建了一个具有ng-pattern的相同模型的隐藏输入,这也不起作用。 So I created a text input with the ng-pattern and hid it via css. 因此,我使用ng模式创建了一个文本输入,并通过CSS隐藏了它。 Which works beautifully. 哪个效果很好。

Is there a smaller work around for this? 是否有较小的解决方案?

EDIT1: I think I should have added that the options are generated by ng-options EDIT1:我认为我应该补充一点,这些选项是由ng-options生成的

EDIT2: Edited the code snippet accordingly to show what I actually want. EDIT2:相应地编辑了代码片段以显示我的实际需求。

 function formCtrl($scope) { $scope.options = ['Please Select','Value 1','Value 2']; $scope.price = 'Please Select'; $scope.onSubmit = function (form) { console.log(form.$valid); } } 
 .show-none { display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-controller="formCtrl"> <form name="myForm" ng-submit="onSubmit(myForm)"> <select ng-model="price" ng-options="o as o for o in options"></select> <input type="text" class="show-none" ng-pattern="/^(?!.*(Please Select))/" ng-model="price" name="price_field"> <span ng-show="myForm.price_field.$error.pattern">Not a valid option!</span> <input type="submit" value="submit" /> </form> </div> 

You shouldn't use ng-pattern with hidden input field for this case, you should add value for each option, & then you should have required attribute make sure any of the option should selected before submiting. 在这种情况下,您不应该将ng-pattern与隐藏的input字段一起使用,您应该为每个选项添加值,然后您应该具有required属性,请确保在提交之前应选择任何选项。 Adding name="price" will add form element to myForm object. 添加name="price"会将表单元素添加到myForm对象。

Markup 标记

<select ng-model="price" name="price" required>
     <option>Please Select</option>
     <option value="TEST1">TEST1</option>
     <option value="TEST2">TEST2</option>
</select>

Update 更新

If you wanted to make it using ng-options then it would be something like below. 如果要使用ng-options进行设置,则如下所示。 You don't need to add Please Select in your array, you could add it manually inside select 您不需要添加“ Please Select ,可以在select手动添加

Markup 标记

<form name="myForm" ng-submit="onSubmit(myForm)" novalidate>
  <select ng-model="price" ng-options="o for o in options" required>
    <option value="">Please select a person</option>
  </select>

  <input type="submit" value="submit" />
</form>

Code

(function(angular) {
  'use strict';
  angular.module('staticSelect', [])
    .controller('formCtrl', ['$scope', function formCtrl($scope) {
      $scope.options = ['Value 1', 'Value 2'];

      $scope.onSubmit = function(form) {
        console.log(form.$valid);
      }
    }]);
})(window.angular);

Demo here 在这里演示

You can also just disable certain options if you didn't want it to be possible to select them in the first place: 如果您不希望首先选择某些选项,则也可以禁用它们:

  <select ng-model="price">
    <option disabled>Please Select</option>
    <option>TEST1</option>
    <option>TEST2</option>
  </select>

Chiming in here as this is something that comes up time and time again and the suggested solutions here don't work for me. 因为这是一次又一次的出现,这里建议的解决方案对我不起作用。 This is a really common use-case too. 这也是一个非常常见的用例。

I tried putting an empty option in, and it didn't work for me. 我尝试放入一个空选项,但对我来说不起作用。 I noticed that AngularJS was placing a value attribute in with the same value as the contents of the <option> tag. 我注意到AngularJS放置了一个value属性,该属性的值与<option>标记的内容相同。 The select was ng-valid even with this option selected. 即使选择了此选项,选择也是ng-valid。

In my scenario I have placed the placeholder option ie SELECT A CENTRE as the first item in the list of locations (the scope variable I bind the options to). 在我的场景中,我将占位符选项(即SELECT A CENTER)作为位置列表中的第一项(我将选项绑定到的范围变量)。 I hide the first item with conditional CSS, but select it initially by setting dc.user.CentreName to SELECT A CENTRE in the controller. 我用条件CSS隐藏了第一项,但是首先通过将dc.user.CentreName设置为控制器中的SELECT A CENTER来选择它。 This gives us the behaviour of it disappearing when the user has clicked any other option. 当用户单击任何其他选项时,这使我们消失了。 Another option is to disable it which means it will still show at the top of the list but will be unselectable after selecting another item (was added in Angular 1.4x). 另一个选项是禁用它,这意味着它仍将显示在列表顶部,但是在选择其他项目后将无法选择(已在Angular 1.4x中添加)。 I have also put that code in (the ng-disabled attribute), to illustrate this. 我也将代码放在( ng-disabled属性)中,以说明这一点。 You may safely remove it if you want to go the hidden route. 如果您想走隐藏路线,可以安全地将其删除。

Next we want to use the standard Angular forms validation to ensure that some item other than the first is selected. 接下来,我们要使用标准的Angular表单验证来确保选择了第一个以外的其他项目。 I tried the other suggested approaches of putting in an empty option (with no value) and setting required on the select. 我尝试了其他建议的方法,即放入一个空选项(无值)并在select上进行设置。 So I went for a hidden input form element with a required and ng-pattern attribute using a negative lookahead assertion. 因此,我使用了否定的前瞻性断言,使用了具有required和ng-pattern属性的隐藏输入表单元素。

Note that we use ng-class to bind ng-valid and ng-invalid to the select so existing CSS styling will work. 请注意,我们使用ng-class将ng-valid和ng-invalid绑定到select上,因此现有的CSS样式将起作用。

Feels a bit hacky but it works. 感觉有点hacky,但是可以用。

<select ng-model="dc.user.CentreName"
        ng-class="{'ng-valid': orderForm.centreName.$valid, 'ng-invalid': !orderForm.centreName.$valid }">
    <option ng-repeat="location in locations"
            ng-disabled="$index < 1"
            ng-style="$index < 1 && {'display': 'none'} "
            value="{{location}}">
        {{location}}
    </option>
</select>

<input
    type="hidden"
    ng-model="dc.user.CentreName"
    ng-pattern="/^(?!SELECT)/"
    required/>

And in the controller... (note you can also use ng-init to set the placeholder value declaratively from the view, see https://stackoverflow.com/a/13775151/4707368 ) 并在控制器中...(请注意,您也可以使用ng-init从视图中声明性地设置占位符值,请参阅https://stackoverflow.com/a/13775151/4707368

function ShoppingController($scope [...]) {

   [...]

    $scope.dc = {
        user: {
            "CentreName": 'SELECT A CENTRE',
   [...]

Your CSS might look like this: 您的CSS可能如下所示:

input.ng-touched.ng-invalid, select.ng-invalid
{
    background-color: rgba(199, 35, 35, 0.15);
}

input.ng-touched.ng-valid, select.ng-valid
{
   background-color: rgba(116, 173, 39, 0.16);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM