Reputation: 3616
I have a select list whose options are based on the selected value. For example, the selected option defaults to 7, and the other four options are always within 2 of this value. So initially [5, 6, 7, 8, 9]
are my options.
If a user selects 5
the select options SHOULD update to [3, 4, 5, 6, 7]
. Indeed the POST request tied to ng-change
fires off successfully and upon page refresh the options are [3, 4, 5, 6, 7]
. My issue is that these options do not update instantly upon option selection. Page refresh is currently necessary to see this change.
Below is relevant code. Basically I'm looking to force the maxOptions
array to update instantly upon option selection.
HTML:
<select ng-options="option for option in linked.maxOptions" ng-model="linked.selectedMax" ng-change="linked.changeMax()"></select>
Controller:
var vm = this;
vm.maxOptions = [];
var getplayerInfo = function() {
playersService.getPlayerInfo({
playerId: playerId
}).$promise.then(function(player) {
vm.player = player;
for (var i = player.max_points - 2; i < customer.max_points + 3; i++) {
vm.maxOptions.push(i);
}
vm.selectedMax = player.max_points;
});
};
var init = function() {
getplayerInfo();
};
init();
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}, {}).$promise.then(function(res){
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};
I'm thinking I need to do something within the $promise
resolution in order to update the UI instantly.
Upvotes: 1
Views: 311
Reputation: 5067
Your maxOptions
array is only updated in getplayerInfo
which is called in init
. There is no code to update the maxOptions
when you call changeMax
. Therefore maxOptions
only gets set on page load but not on change.
You need to do something like this in your changeMax.
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}, {}).$promise.then(function(res){
vm.player.max_points = vm.selectedMax;
vm.maxOptions = [];
for (var i = player.max_points - 2; i < customer.max_points + 3; i++) {
vm.maxOptions.push(i);
}
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};
Or better yet, abstract the building of the array as a model method like this and call it from both functions:
vm.updateMaxOptions = function() {
vm.maxOptions = [];
for (var i = player.max_points - 2; i < customer.max_points + 3; i++) {
vm.maxOptions.push(i);
}
};
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}, {}).$promise.then(function(res){
vm.player.max_points = vm.selectedMax;
vm.updateMaxOptions();
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};
Upvotes: 1