从select下拉angularjs中删除空项

时间:2017-06-28 10:26:02

标签: javascript angularjs

我正在尝试绑定数据以使用AngularJS ng-repeat指令选择下拉列表,但它在页面加载时显示空数据。如何删除空项目。 这是代码:

    <html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
      <select ng-model="selected">
        <option ng-repeat="item in items" value="{{item.id}}">
          {{item.name}}
        </option>
      </select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

这是JS代码:

var app = angular.module('app',[]);
            app.controller('homeCtrl',['$scope',function($scope){
                $scope.selected = 1;
                $scope.items=[
                    {name: 'harry111',id:1},
                    {name: 'rimmi',id:2}
                ];

            }]);

这是DEMO

3 个答案:

答案 0 :(得分:1)

改为使用ng-options,

 ng-options="value.id as value.name for (key,value) in items"

<强>样本

var app = angular.module('app',[]);
			app.controller('homeCtrl',['$scope',function($scope){
  		$scope.items=[
					{name: 'harry111',id:1},
					{name: 'rimmi',id:2}
				];
				   $scope.selected = $scope.items[0].id;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
     <select ng-model="selected" ng-options="value.id as value.name
                                           for (key,value) in items"
  ></select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

答案 1 :(得分:1)

$scope.selected = 1;设为$scope.selected = "1";,默认选择值

var app = angular.module('app',[]);
			app.controller('homeCtrl',['$scope',function($scope){
				 $scope.selected = "1";
				$scope.items=[
					{name: 'harry111',id:1},
					{name: 'rimmi',id:2}
				];
        
       
         
       
				
			}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
      <select ng-model="selected">
        <option ng-repeat="item in items" value="{{item.id}}">
          {{item.name}}
        </option>
      </select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

答案 2 :(得分:0)

您需要在ng-repeat代码中添加<select>,例如

<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
      <select ng-model="selected" ng-options="value.id as value.name
                                           for (key,value) in items"
  ></select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

这不会在选择下拉列表中添加空白选项。这是工作CODEPEN