kairi
kairi

Reputation: 308

Remove empty option when ng-model is added in dropdown (AngularJS 1.4)

Im currently doing a dropdown and getting the data via angular JS, but whenever i add ng-model="email_mobile" it adds an empty field enter image description here and I cant remove it, i tried doing the correct answers here but I dont think that its applicable because I am getting 2 values in 1 array:

JS

   $scope.configs = [
      {'email': '[email protected]',
      'phone': '123',
       'value': 'config1'},
    ];

$scope.getValue = function(){
  $scope.value =$scope.email_mobile;
  console.log($scope.value )
}

blade

        <select class="form-control" name="email_mobile" id="email_mobile" ng-model="email_mobile" ng-change="getValue()" required>
          <option data-ng-repeat="x in configs" ng-if="x.email" value="@{{x.email}}" selected>@{{x.email}}</option>
          <option data-ng-repeat="x in configs" ng-if="x.phone" value="@{{x.phone}}" selected>@{{x.phone}}</option>
        </select>

another thing is, the reason why my code is like that, because I also need to get the value of ng-model="email_mobile" on change. I only need to remove the empty value while still getting the value of the dropdown on change

Upvotes: 2

Views: 271

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You can achieve this by setting the default value of select in the format of your options' value:

$scope.email_mobile = "@" + $scope.configs[0].email;

Check code below:

angular.module("myApp", [])
  .controller("myCtrl", function($scope) {
    $scope.configs = [{
      'email': '[email protected]',
      'phone': '123',
      'value': 'config1'
    }];
    
    $scope.email_mobile = $scope.configs[0].email;
    
    $scope.getValue = function() {
      $scope.value = $scope.email_mobile;
      console.log($scope.value)
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <select class="form-control" name="email_mobile" id="email_mobile" ng-model="email_mobile" ng-change="getValue()" required>
    <option data-ng-repeat="x in configs" ng-if="x.email" value="{{x.email}}" selected>{{x.email}}</option>
    <option data-ng-repeat="x in configs" ng-if="x.phone" value="{{x.phone}}" selected>{{x.phone}}</option>
  </select>
</div>

Upvotes: 2

Related Questions