简体   繁体   English

为什么使用angularJs的select选项显示第一个空选项?

[英]Why does select option using angularJs show first empty option?

When I reload the page, the first option is always empty. 重新加载页面时,第一个选项始终为空。 I want the option containing text Any Make to be the default select option. 我希望包含文本Any Make的选项成为默认选择选项。 Here is the code for my view: 这是我的看法的代码:

  <select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
      <option value="0" selected="selected"> Any Make</option>
      <option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
  </select>

here is my controller code: 这是我的控制器代码:

.controller("homeController", function ($scope, makeData, $http) {

            $scope.makeData = makeData;

            $scope.makeChanged = function () {
                $http({
                    method: "GET",
                    url: "homeService.asmx/GetModelById"})
                    .then(function (response) {
                        $scope.modelData = response.data;
                })
            }
        })

just remove ng-init and in your model give default value 只需删除ng-init并在模型中提供默认值

   $scope.makeSelected = 0;

Here is a running fiddle for your code Click here 这是您的代码运行的小提琴点击这里

Fiddle for code with dynamic data Click here 拨弄具有动态数据的代码,请单击此处

If you aren't going to use ngOptions , at least get rid of that ng-init since it isn't a function, and in the controller function set $scope.makeSelected = 0 ; 如果您不打算使用ngOptions ,那么至少要摆脱该ng-init因为它不是一个函数,在控制器函数中设置$scope.makeSelected = 0

Then you can remove the selected="selected" on that initial option, since the angularJS code will be handling what is selected. 然后,您可以在该初始选项上删除selected="selected" ,因为angularJS代码将处理所选内容。

See a demonstration below: 请参见下面的演示:

 angular.module('app', []) .value('makeData', [{ "make_id": 1, "make_name": "cat" },{ "make_id": 2, "make_name": "dog" },{ "make_id": 6, "make_name": "monkey" }]) .controller("homeController", function($scope, makeData, $http) { //initialize the value associated with ng-model on the select list $scope.makeSelected = 0; $scope.makeData = makeData; $scope.makeChanged = function() { console.log('makeChanged'); //$http() request removed because we don't have access outside this domain for AJAX requests. }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="homeController"> <select class="form-control" id="make" name="make" ng-model="makeSelected" ng-change="makeChanged()"> <option value="0"> Any Make</option> <option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option> </select> <div>makeSelected: {{makeSelected}}</div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM