Menu

Select Value Not Selected In Angularjs

When selecting options from a dropdown, type matters for binding purposes. When using ng-options, you can use as to bind something to the model as a non-string value. In your case, you may want to bind to the integer value of the id.

Syntax: select as label for value in array

> select: The value that gets bound to ng-model
> label: What value visibly shows up in the dropdown
> value: Current item in array
> array: Data source for generating the options

Example of binding to an integer value:

Angular js:

 


 

var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
  $scope.props = [{Grade: 1}];
  $scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];

});

 

HTML :

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">script>
<div ng-app="myApp" ng-controller="myCtrl">
  Binding with an integer value:
  <div ng-repeat="prop in props" style="margin-bottom: 10px;">
    <label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})label>
    <div class="col-md-8">
      <select ng-model="prop.Grade" class="form-control" ng-options="opt.id as opt.name for opt in propGradings">
        <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}option>
      select>
    div>
  div>
div>

 

678
Search

Ads