Check out this plunker example
I have a collection of cars and their corresponding available years:
- ["Volvo", "VW", "Audi"] --> [2006, 2007, 2008]
- ["Ford", "Honda", "Jaguar"] --> [2008, 2009, 2010, 2011]
Note: The year 2008 is duplicated. This is important)
By default, I have assigned the year 2006 (any year besides 2008) for Volvo.
Click "Load car 1", then "Load car 2".
You will observe that 2006 is displayed. It functions correctly.
However, when switching from 2006 to 2008.
Click "Load car 1", then "Load car 2".
2008 disappears. It fails to function properly.
Why is this happening? What am I missing or not comprehending? The value type for SELECT tag doesn't matter (number or string)
If I remove
//I use length = 0 in ng-disabled to prevent user from changing 'year' during timeout interval
if (main.years) main.years.length = 0;
or $timeout, it functions correctly.
Even after trying to use bind, it still didn't work.
Thank you.
Although my example is simple, in my actual project, with numerous fields and a slow client-server system. Furthermore, if I rapidly select cars, the data in cars array and options in the select get lost
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($timeout) {
var main = this;
main.selectCar = selectCar;
main.models = ["Volvo", "VW", "Audi", "Ford", "Honda", "Jaguar"];
//main.years = [2006, 2007, 2008, 2009, 2010, 2011];
main.cars = [{
year: 2006,
model: "Volvo"
}, {
year: 2011,
model: "Honda"
}];
selectCar(main.cars[0]);
// bind also does not work
function selectCar(car) {
// I use length = 0 in ng-disabled to prevent user from changing 'year' during timeout interval
if (main.years) main.years.length = 0; //will work without this line
main.activeCar = car;
getDataFromServer('years');
console.log(main.cars[0].year);
}
function getDataFromServer(nameForOptions) {
// don't think about this logic
// $q
$timeout(function() { //will work without $timeout
var arr;
if (nameForOptions === 'years') {
if (["Volvo", "VW", "Audi"].indexOf(main.activeCar.model) > -1) {
arr = [2006, 2007, 2008];
} else {
arr = [2008, 2009, 2010, 2011];
};
}
main[nameForOptions] = arr;
}, 100);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl as main">
<br /><br />
<button ng-click="main.selectCar(main.cars[0])">Load car 1</button>
<button ng-click="main.selectCar(main.cars[1])">Load car 2</button>
<br /><br />
<select id="select_1" ng-model="main.activeCar.model" ng-options="model for model in main.models" ng-disabled="!main.models.length"></select>
<select id="select_2" ng-model="main.activeCar.year" ng-options="year for year in main.years" ng-disabled="!main.years.length"></select>
<hr />
<p>Cars:</p>
<ol>
<li ng-repeat="car in main.cars">{{car.model}} - {{car.year}}</li>
</ol>
</body>