Lars Mertens Lars Mertens - 1 month ago 7
AngularJS Question

Selected value not displayed on AngularJS Select

My problem is when i change the value of the dropdown menu the value isn't displayed in the dropdown menu but the correct value is displayed in my console. Not sure why it isn't working at the moment because i have a same implementation of this in another project. Maybe i'm overlooking things.


On initialization i set


selected_type = types[0]
// What will result in Type1 being displayed on page load.



Fiddle you can find here: https://jsfiddle.net/596tzsh8/7/

Answer

Use:

ng-options="selected_type as selected_type.Name for selected_type in types track by selected_type.Id"
//                 ^
//         the object itself

... instead of:

ng-options="selected_type.Id as selected_type.Name for selected_type in types track by selected_type.Id"
//                  ^
//            the object's ID

Then, in your callback function, replace:

var typeID = this.selected_type;
//                      ^
//              the object itself

... by:

var typeID = this.selected_type.Id;
//                        ^
//                 the object's ID

... and you're all set!

See your forked JSFiddle here, or play around with the snippet below.

var app = angular.module("app", ["controllers"])

var controllers = angular.module("controllers",[]);
controllers.controller('myController', function($scope){

	$scope.types = [{
            Id: 1,
            Name: 'Type1'
        }, {
            Id: 2,
            Name: 'Type2'
        }, {
            Id: 3,
            Name: 'Type3'
  }];

  $scope.GetValueTypeDropdown = function () {
  	var typeID = this.selected_type.Id;
    	$scope.the_type = $.grep($scope.types, function (selected_type){
      	return selected_type.Id == typeID;
      })[0].Name;
      console.log($scope.the_type);
    return $scope.the_type;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="myController">
      <form>
          <select name="type" class="col-xs-12 dropdown-list"
                  ng-model="selected_type" class="col-xs-8"
                  ng-init="selected_type = types[0]"
                  ng-options="selected_type as selected_type.Name for   selected_type in types track by selected_type.Id"
                  ng-change="GetValueTypeDropdown()">
          </select>
      </form>
    </div>
</div>

Comments