Shaur Bin Talib
Shaur Bin Talib

Reputation: 95

Why does select option using angularJs show first empty option?

When I reload the page, the first option is always empty. I want the option containing text Any Make to be the default select option. Here is the code for my view:

  <select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
      <option value="0" selected="selected"> Any Make</option>
      <option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
  </select>

here is my controller code:

.controller("homeController", function ($scope, makeData, $http) {

            $scope.makeData = makeData;

            $scope.makeChanged = function () {
                $http({
                    method: "GET",
                    url: "homeService.asmx/GetModelById"})
                    .then(function (response) {
                        $scope.modelData = response.data;
                })
            }
        })

Upvotes: 0

Views: 76

Answers (2)

Varun Sukheja
Varun Sukheja

Reputation: 6548

just remove ng-init and in your model give default value

   $scope.makeSelected = 0;

Here is a running fiddle for your code Click here

Fiddle for code with dynamic data Click here

Upvotes: 1

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

If you aren't going to use ngOptions, at least get rid of that ng-init since it isn't a function, and in the controller function set $scope.makeSelected = 0;

Then you can remove the selected="selected" on that initial option, since the angularJS code will be handling what is selected.

See a demonstration below:

angular.module('app', [])
  .value('makeData', [{
    "make_id": 1,
    "make_name": "cat"
  },{
    "make_id": 2,
    "make_name": "dog"
  },{
    "make_id": 6,
    "make_name": "monkey"
  }])
  .controller("homeController", function($scope, makeData, $http) {
    //initialize the value associated with ng-model on the select list
    $scope.makeSelected = 0;
    $scope.makeData = makeData;

    $scope.makeChanged = function() {
      console.log('makeChanged');
      //$http() request removed because we don't have access outside this domain for AJAX requests.
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeController">
  <select class="form-control" id="make" name="make"  ng-model="makeSelected" ng-change="makeChanged()">
      <option value="0"> Any Make</option>
      <option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
  </select>
  <div>makeSelected: {{makeSelected}}</div>
</div>

Upvotes: 0

Related Questions