Naguib Ihab
Naguib Ihab

Reputation: 4496

select tag with ng-model not showing the correct option

So this is my code:

<select ng-model="institution.data_collection" class="form-control" required>
  <option value="" disabled>Please Select</option>
  <option value="109">24 Hours</option>
  <option value="107" onselect="">School Hours</option>
</select>

institution.data_collection value is equal to 109 and I expected the option 24 Hours to be selected since it has a value of 109. But what happens is I find a new option added in the select tag:

<option value="? number:109 ?"></option>

Going through SO questions I find that most people defined the options in an array in the controller which may be the better practice in that case and would solve my issue, however, I still want to understand what is happening.

Upvotes: 0

Views: 566

Answers (3)

Ankit Vadi
Ankit Vadi

Reputation: 475

Make $scope.institution.data_collection = "109", it must work. Any HTML element sets its value as string not as a number by default, so you will need to assign string value to its model to work fine. Other option is to use ng-options, then you will be able to assign numeric value as model.

Upvotes: 1

Snopzer
Snopzer

Reputation: 1692

<select ng-model="institution.data_collection" ngChange="expression()" class="form-control" required>
  <option value="?">Please Select</option>
  <option value="109">24 Hours</option>
  <option value="107">School Hours</option>
</select>

You should not write "onselect" for option, you have to assign that attribute to select tag.

Script :

$scope.expression = function (){
 $scope.institution // selected value
// write your logic here
}

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222522

You need to set the $scope variable in the controller

$scope.institution ={};
$scope.institution.data_collection = '109';

DEMO

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

app.controller("ListCtrl", ["$scope",
  function($scope) {
    $scope.institution ={};
    $scope.institution.data_collection = '109';
  }
]);
<!DOCTYPE html>
<html>

<head>
  <script data-require="[email protected]" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app='app'>
  <div ng-controller="ListCtrl">
   <select ng-model="institution.data_collection" class="form-control" required>
  <option value="" disabled>Please Select</option>
  <option value="109" ng-selected="">24 Hours</option>
  <option value="107" onselect="">School Hours</option>
</select>
  </div>
</body>

</html>

Upvotes: 2

Related Questions