简体   繁体   中英

Angularjs dropdown validation not working

Hi I am developing web application in angularjs. I have one dropdown. Below is my dropdown code.

 <div class="inputblock" ng-class="{ 'has-error' : ((form2.$submitted && form2.period.$invalid)  || (form2.period.$invalid && form2.period.$dirty))}">
   <div>
   <span class="ang-error" style="color:#fff" ng-show="form2.period.$dirty && form2.period.$invalid">Select service</span>
   </div>
   <select class="with-icon"  ng-model="user.period" name="period" id="period" ng-options="user.ID as user.period for user in periodList" required>
   <option value="" label="{{ 'Period' | translate }}">{{ 'Period' | translate }}</option>
   </select>
   </div>

Below is my js code.

  $scope.periodList = [{ id: 1, period: '1 Month' }];

I am facing below multiple issues. By default when page loads first value will bind but i want to display Period. I am not sure why this is happening When i select some value I can see invalid and fires error message. I captured below code from the browser.

  <select class="with-icon ng-invalid ng-invalid-required ng-touched ng-dirty" ng-model="user.period" name="period" id="period" ng-options="user.ID as user.period for user in periodList" required=""><option value="" label="Period" class="ng-binding" selected="selected">Period</option><option value="undefined:undefined" label="1 Month" selected="selected">1 Month</option></select>

May i know what i am doing wrong with above dropdown. Any help would be appreciated. Thank you.

In your controller

$scope.items = [{
      id: 1,
      label: 'aLabel'
    }, {
      id: 2,
      label: 'bLabel'
    }];

    $scope.selected = $scope.items[0];

In template, if you have bootstrap use this same class, otherwise you can create your own class

<form name="abcd" novalidate>
    <div class="form-group" ng-class="{'has-error': abcd.select.$dirty && abcd.select.$invalid }">
    <select name="select" ng-options="item as item.label for item in items track by item.id" ng-model="selected" required></select>
    </div>
    <div ng-messages="abcd.select.$dirty && abcd.select.$error">
        <div ng-messages="required">This is required</div>
    </div>
</form>

Change your select. id is the key you have to reference from $scope.periodList

 <select class="with-icon"  ng-model="user.period" name="period" id="period" ng-options="user.id as user.period for user in periodList" required>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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