Reputation: 1254
I am using Angular's ng-init to load a rest call function and it fills up $scope.races then it fills up the dropdown.
At first load everything seems fine. But when I click the dropdown menu and select an option. Dropdown immediately becomes empty.
I assume someway $scope.races becomes empty.
This is my Angular controller:
angular.module('MyApp', [])
.controller('RestController', function($scope, $http) {
$scope.getRaces = function() {
$http.get('http://localhost:8080/races').
success(function(data) {
$scope.races = data;
});
}
});
This is HTML:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="restController.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-app="MyApp" ng-controller="RestController">
<div class="container-fluid" ng-init="getRaces()">
<select ng-model="races">
<option ng-repeat="race in races" value="{{race.raceId}}">{{race.raceName}}</option>
</select>
</div>
</body>
</html>
Upvotes: 0
Views: 256
Reputation: 1652
Remove ng-model="races", as you are re setting it in . Here is working sample.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="restController.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-app="MyApp" ng-controller="RestController">
<div class="container-fluid" ng-init="getRaces()">
<select>
<option ng-repeat="race in races" value="{{race.raceId}}">{{race.raceName}}</option>
</select>
</div>
<script>
angular.module('MyApp', [])
.controller('RestController', function($scope, $http) {
$scope.getRaces = function() {
var data = [{raceId:'1',raceName:'nam1'},{raceId:'12',raceName:'nam2'},{raceId:'13',raceName:'nam13'}];//get data from http
$scope.races = data;
// $http.get('http://localhost:8080/races').
// success(function(data) {
// $scope.races = data;
// });
}
});
</script>
</body>
</html>
Upvotes: 2
Reputation: 142
your issue is ng-model="races" on your select is over-writing the $scope.races in your restController.js as soon as you select an option. Rename ng-model="races" to something like ng-model="racesSelection" and use this as the variable to determine what option was selected
Upvotes: 1