Selecting an option before ngOptions knows about it: Objects
HTML
<body ng-app="demoApp">
← Change the Angular version here (JavaScript settings button) & Run again
<br/>
<div ng-controller="DemoController">
<h3>Selecting an option before ngOptions knows about it</h3>
<P>Clicking the button below sets <b>selectedId</b> to 3, but there is no corresponding option in the array maintained by the <b>ngOptions</b> directive until <i>after</i> 3 is selected. This is okay in Angular 1.2.1, but we get too many digest iterations in 1.4.8 (see console). This also <a href="http://jsfiddle.net/x15jccmj/3/">works fine</a> if our options are values instead of objects.</P>
<select ng-model="selectedId" ng-options="opt.id as opt.label for opt in getOptions()">
</select>
<i>The value selected is {{ selectedId }}.</i>
<br/>
<br/>
<button ng-click="setSelectedIdTo3()">Select 3!</button>
</div>
</body>
<link href="http://fonts.googleapis.com/css?family=Ubuntu:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
CSS
body {
font-family: 'Ubuntu', Arial;
color: #660066;
font-size: 14px;
}
div {
font-size: 16px;
padding: 5px 20px 20px;
background-color: rgba(204, 0, 204, .1);
margin-top: 10px;
}
select {
color: #330033;
padding-left: 5px;
padding-right: 5px;
border: 1px solid #660066;
height: 30px;
border-radius: 3px;
width: 65px;
margin-right: 10px;
}
button {
padding: 6px 12px;
font-size: 14px;
font-weight: 600;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
color: white;
background-color: rgba(204, 0, 204, .8);
}
JavaScript
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.options = [
{ id: 1, label: 'one' },
{ id: 2, label: 'two' }];
$scope.getOptions = function() {
if ($scope.selectedId == 3)
return [{ id: 3, label: 'three' }].concat($scope.options);
else
return $scope.options;
};
$scope.selectedId = 1;
$scope.setSelectedIdTo3 = function() {
$scope.selectedId = 3;
};
});