AngularJS: after ng-change 1st select is getting empty

Problem

I am using following code to get data from local json file and populating two dropdowns from it but after ng-change event fires 1st dropdown is empty.

   $http({method: 'GET', url: 'data/local.json'}).
        success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available

      var _data=data;
      $scope.places=[];
      $scope.toPlaces=[];
      $scope.places=data;
      $scope.getToPlaces=function(){
      var selected=$('#fromSelect :selected').val();
      console.log($scope.places[1]);
      var key=$scope.places[1]
      $scope.toPlaces = _data[key].to;               
    }                 
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("failure");
    });

I am using code from this link: https://github.com/marcoslin/angularAMD and passing json file from my local machine.

After ng-change 1st select is getting empty.

Problem courtesy of: asdfdefsad

Solution

The problem is within your markup:

From angular docs:

When an item in the menu is selected, the array element or object property represented by the selected option will be bound to the model identified by the ngModel directive.

This is the reason why it overrides the places array when it is selected.

The ngModel directive inside a select tag should just refer to another variable on the scope:

<select ng-model="selectedPlace" ng-change="getToPlaces()" id="fromSelect">
    <option value="">--Please select From place</option>
    <option ng-repeat="p in places" value="{{p.id}}">
        {{p.name}}
    </option>
</select>

Now instead of var selected=$('#fromSelect :selected').val(); , You can just refer to that varaible:

var selected = $scope.selectedPlace;
Solution courtesy of: Ilan Frumer

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.