Unable to set default selected option in selection tag

709 views Asked by At

I have encountered issue with angular.js 1.4.0. I can't set the default in select tag if I will use a 'number' but it will work if I use a 'string'. The select statement is hard code in the view. I already initialize my model in the controller.

// This will NOT WORK, value passed is a 'number' $scope.colors = 2;

// This will WORK, value passed is a 'string' $scope.colors='2';

VIEW/MODEL:

<div ng-app="app">
  <div ng-controller="MyController">
    <select ng-model="colors">
      <option value="1">Red</option>
      <option value="2">Blue</option>
      <option value="3">Green</option>
    </select>
    <p>Selected Color: {{colors}}</p>
    <div ng-switch="colors">
      <p ng-switch-when="1"><span class="red-block"></span></p>
      <p ng-switch-when="2"><span class="blue-block"></span></p>
      <p ng-switch-when="3"><span class="green-block"></span></p>
    </div>
</div>

CONTROLLER:

angular.module('app', []).controller('MyController', function($scope) {
   /* angular.js version 1.4.0 issue: 
      $scope.colors = 2; --> will not work
      $scope.colors = '2'; --> will work

      This is working on angular.js version 1.3.15
   */
   $scope.colors = 1;
});

If I use angular.js version 1.3.15, both 'number' and 'string' will work.

Note: angular version set in codepen is 1.4.0 so you can see the error.

http://codepen.io/joemalski/pen/YXQMKO?editors=001

2

There are 2 answers

1
Hardy On

JS:

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];

HTML:

<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>

This would leave the "b" item to be selected.

1
Freezystem On

Ok, instead of having a static select/option use a dynamic one :

$scope.colors = ["red","blue","green"];

in your HTML

<select ng-model="selectedColor" ng-option="color in colors"></select>

<div ng-switch="selectedColor">
    <p ng-switch-when="red"><span class="red-block"></span></p>
    <p ng-switch-when="blue"><span class="blue-block"></span></p>
    <p ng-switch-when="green"><span class="green-block"></span></p>
</div>

use string like so you'll be safe.