Search code examples
javascriptangularjsng-options

Auto select new added value with ng-options and AngularJS


I have a select list looking like this:

<select 
  class="form-control" 
  ng-model="locationList" 
  ng-options="location.place group by location.type for location in locationlist | orderBy:['type']" 
  ng-change="addMissingLocation(locationList)">

    <option value="">From</option>
</select>

The last item of the ng-options list is called "Add location", and triggers the following function through ng-change:

$scope.addMissingLocation = function (locationList) {
    if (locationList.place == "Add location") {
        $('.addMissingLocation').modal('show');
    }
}

A modal shows, and it allows the user to add a new location using the following function:

$scope.addLocationOtherExtra = function () {
    $scope.locationlist.push({ place: $scope.formLocationOther, type: "-Secondary Locations", main:false});
    jsonToLocationLocalStorage($scope.locationlist);
    $scope.formLocationOther = '';
    $('.addMissingLocation').modal('hide');
};

What I am trying to accomplish, is that once the user introduces a new location and the modal closes, the selected value in the select, is this newly added value.

I'm not even sure if such thing is possible.

Any tips?


Solution

  • After adding new option you should point ngModel to added option. Try this to select the last option (new one):

    $scope.addLocationOtherExtra = function () {
    
        $scope.locationlist.push({ place: $scope.formLocationOther, type: "-Secondary Locations", main:false});
        $scope.locationList = $scope.locationlist[$scope.locationlist.length - 1];
    
        jsonToLocationLocalStorage($scope.locationlist);
        $scope.formLocationOther = '';
        $('.addMissingLocation').modal('hide');
    };