2

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.

2
  • Shouldn't your ng-options be user.id instead of user.ID Commented Aug 11, 2017 at 5:15
  • 1
    Yes. This fixed my issue Commented Aug 11, 2017 at 5:23

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.