ng-options is hiding the blank value with AngularJS V1.5 [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-25 00:50:10

问题


I followed the instructions specified in the V1.3 documentation to have a default option in one of my selects.

Therefore in my Angular ̶1̶.̶3̶.̶1̶5̶   1.5.7 template I have:

  <div class="form-group">
    <div class="col-md-12">
      <select ng-model="selectedObj" class="form-control"
              ng-options="obj.id as obj.name for obj in objects">
        <option value="">All objects</option>
      </select>
    </div>
  </div>

and in my controller I initialise it with:

$scope.selectedObj = '';
$scope.objects = [
  {
    id: '1',
    name: 'A',
  },
  {
    id: '2',
    name: 'B',
  },
  {
    id: '3',
    name: 'C',
  },
];

What happens is that the "All objects" option is not shown and instead the default "blank option" is shown and is only selectable the first time. The blank option is probably the one described here.

How can I make my default option work in place of the default one? What am I missing?


I've just found out the Angular version inside bower_components/angular/.bower.json is specified as 1.5.7 as opposed to what the main bower.json file specifies (which is 1.3.15).

May this be the cause for the seemingly weird behaviour?


回答1:


The problem is with your controller.

Don't initialize your $scope.selectedObj.

Updated controller:

$scope.objects = [
  {
    id: '1',
    name: 'A',
  },
  {
    id: '2',
    name: 'B',
  },
  {
    id: '3',
    name: 'C',
  },
];

Here is a working example:

https://stackblitz.com/edit/angularjs-twzxrk?file=home%2Fhome.html




回答2:


Set the ng-model to null:

 ̶$̶s̶c̶o̶p̶e̶.̶s̶e̶l̶e̶c̶t̶e̶d̶O̶b̶j̶ ̶=̶ ̶'̶'̶;̶
 $scope.selectedObj = null;

The ng-option directive was heavily refactored in V1.4 and many bugs removed in V1.5. For more information, see

  • AngularJS Developer Guide - Migrating to V1.4 - ng-options
  • AngularJS Developer Guide - Migrating to V1.5 - directives ng-options

The DEMO

angular.module('app',[])
.controller("ctrl",function($scope) {
    $scope.selectedObj = null;
    $scope.objects = [
    {
        id: '1',
        name: 'A',
      },
      {
        id: '2',
        name: 'B',
      },
      {
        id: '3',
        name: 'C',
      },
    ];
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
     <select ng-model="selectedObj" class="form-control"
             ng-options="obj.id as obj.name for obj in objects">
        <option value="">All objects</option>
     </select>
</body>


来源:https://stackoverflow.com/questions/51211056/ng-options-is-hiding-the-blank-value-with-angularjs-v1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!