2017-06-28 169 views
1

我試圖綁定數據以使用AngularJS ng-repeat指令選擇下拉菜單,但它在頁面加載時顯示空數據。如何刪除空的項目。 下面是代碼:從選擇下拉列表中刪除空的項目angularjs

<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

+0

看答案被張貼。那是你需要的。 –

+1

答案很簡單,由@SrinivasML發佈,但更好地使用ng-options代替作爲一種良好的習慣。 –

回答

1

使$scope.selected = 1;$scope.selected = "1";它會默認選擇值

var app = angular.module('app',[]); 
 
\t \t \t app.controller('homeCtrl',['$scope',function($scope){ 
 
\t \t \t \t $scope.selected = "1"; 
 
\t \t \t \t $scope.items=[ 
 
\t \t \t \t \t {name: 'harry111',id:1}, 
 
\t \t \t \t \t {name: 'rimmi',id:2} 
 
\t \t \t \t ]; 
 
     
 
     
 
      
 
     
 
\t \t \t \t 
 
\t \t \t }]);
<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>

+0

爲什麼「1」而不是1? – iJade

+0

我正在尋找這個問題,我曾經遇到過這個問題,當轉換爲字符串它被選中,檢查SO問題以添加引用 –

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> 

這不會添加blan選擇下拉菜單中的k選項。這裏是工作CODEPEN

+1

但我沒有看到ng -repeat – iJade

+0

看到那裏,有ng選項遍歷items數組。 –

1

使用NG選項代替,

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

DEMO

var app = angular.module('app',[]); 
 
\t \t \t app.controller('homeCtrl',['$scope',function($scope){ 
 
    \t \t $scope.items=[ 
 
\t \t \t \t \t {name: 'harry111',id:1}, 
 
\t \t \t \t \t {name: 'rimmi',id:2} 
 
\t \t \t \t ]; 
 
\t \t \t \t $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>

相關問題