单击后,HTML下拉列表元素消失

时间:2016-07-11 17:06:12

标签: javascript angularjs

我正在使用Angular的ng-init来加载一个休息调用函数,它填满了$ scope.races然后它填满了下拉列表。

首先加载一切似乎都很好。但是当我单击下拉菜单并选择一个选项时。下拉立即变空。

我假设$ scope.races变为空。

这是我的Angular控制器:

angular.module('MyApp', [])
.controller('RestController', function($scope, $http) {

    $scope.getRaces = function() {
        $http.get('http://localhost:8080/races').
        success(function(data) {
            $scope.races = data;
        });
    }
});

这是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>

2 个答案:

答案 0 :(得分:2)

删除ng-model =&#34;比赛&#34;,当您重新设置时。这是工作样本。

   <!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>

答案 1 :(得分:1)

你的问题是ng-model =&#34;比赛&#34;一旦选择了一个选项,你的select就会覆盖restController.js中的$ scope.races。重命名ng-model =&#34;比赛&#34;像ng-model =&#34; racesSelection&#34;并使用它作为变量来确定选择了哪个选项