2016-12-10 449 views
0

我正在使用AngularJS來呈現我的頁面。我需要具有相同數據的2個選擇器,所以我使用了一個控制器。數據應該由GET請求接收,並且我想添加一個默認選擇的額外選項。我已經試圖通過將響應與{id:-1, name:"All"}.concat($scope.dfleets)之類的選項相連來進行添加,但嘗試失敗。 很明顯,該選項應該添加在HTML內。下面的代碼創建了一個適當的選擇列表,但selectCtrl.selectedValue = selectCtrl.defaultValue.id似乎沒有效果,並且在頁面加載時未選擇任何項目。AngularJS - 如何設置默認選擇選項

html頁面

<div ng-controller="SelectController as selectCtrl"> 
<select ng-model="selectCtrl.selectedValue" class="form-control" id="selectFleet_1" ng-init="showDriversFleets()"> 
    <option value="selectCtrl.defaultValue.id">{[{selectCtrl.defaultValue.name}]}</option> 
    <option ng-repeat="value in selectCtrl.values" value="{[{value.id}]}">{[{value.name}]}</option> 
</select> 

js代碼

dApp.controller('SelectController', ['$scope', '$http', function ($scope, $http){ 

$scope.showDriversFleets = function() { 
    $scope.dfleets = []; 

    $http.get('/api/driver/fleets/').then(function (res) { 
     return angular.forEach(res.data, function (item) { 
      return $scope.dfleets.push(item); 
     }); 
    }); 
} 

var selectCtrl = this; 
selectCtrl.defaultValue = {id:-1, name:"All"} 
selectCtrl.values = $scope.dfleets; 
selectCtrl.selectedValue = selectCtrl.defaultValue.id; 
}]); 
+0

你用ng-init試過嗎? – Sajeetharan

+0

我已經使用ng-init和函數我應該設置默認 – NomaD

回答

1

這裏有兩種方式plunker示範可以工作 https://plnkr.co/edit/xx8ZjBdy55sgyIYdcNAw?p=preview

我有更復雜首先會讓你自定義選擇下拉菜單的方法。

我想它應該在一個單獨的指令。它在控制器中需要更多的操縱,而不是我認爲的好形式。

我當然不是專家 - 不一定是肯定的最佳做法

第二個版本包括我更接近到什麼是他們的文檔中,以便也許你應該使用方法。

<html ng-app="selectListNgDefault"> 
<head> 
    <title>Check-box to toggle list</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">  </script> 
    <script src="selectListAngularSO.js"></script> 
    <style type="text/css" media="screen"> 
    .left{ background-color: pink; width: 250px; height: 150px; display: inline-block; float: left;} 
    .right{ background-color: beige; width: 250px; height: 150px; display: inline-block; float: left;} 
    .demonstration{display:inline-block; border: 1px solid black; clear: both;} 
    .processing-message{width: 500px; background-color: yellow; display:inline-block; border: 1px solid black; clear: both;} 
    </style> 
</head> 

<body ng-controller="defaultAllSelectListCtrl" ng-init="checkedList=true"> 
    <div class="demonstration"> 
    <div class="left"> 
     <h3>Using ng-repeat for selection</h3> 
     <label >Select a Fleet</label> 
     <select ng-init="selectedFleet=dfleets[0].id" ng-model="selectedFleet" ng-change="handleFleetSelectionFromString(selectedFleet)"> 
     <option ng-repeat="fleet in dfleets" value="{{fleet.id}}" >{{fleet.brand}}({{fleet.cars}})</option> 
     </select> 

     <p>There are {{dfleets.length - 1}} fleet brands</p> 
     </div> 
    <div class="right"> 
     <h1><em>{{selectedFleetFromId.brand}}</em> Drivers</h1> 
     <h2>Have {{selectedFleetFromId.cars}} cars!</h2> 
    </div> 
    </div> 

    <div class="demonstration"> 
    <div class="left"> 
     <h3>Using ng-options for selection</h3> 
     <label >Select a Fleet</label> 
     <select ng-init="ngOptionsSelectedFleet=dfleets[0]" ng-model="ngOptionsSelectedFleet" ng-options="v.brand for (k,v) in dfleets" ng-change="handleFleetSelection(ngOptionsSelectedFleet)"></select> 
    </div> 
    <div class="right"> 
     <h1>{{ngOptionsSelectedFleet.brand}} Drivers</h1> 
     <h2>Have {{ngOptionsSelectedFleet.cars}} cars!</h2> 
    </div> 
    </div> 
    <br> 
    <div ng-hide="hideProcessingMessage" class="processing-message"> 
    Alert: {{processingMessage}} 
    </div> 
</body> 
</html> 

及以下JS文件

var app = angular.module('selectListNgDefault', []) ; 


    app.controller('defaultAllSelectListCtrl', function ($scope, $http) { 
    var dummyData = [{id: "id1", brand: "Ford", cars: 12},{ id: "id2", brand: "Volkswagen", cars: 11},{id: 'id3', brand: "Mercedes", cars: 6},{id:"id4", brand: "Toyota", cars: 2},{id: "id5", brand: "Honda", cars: 19}]; 
    $scope.hideProcessingMessage = true; 

    $scope.showDriversFleets = function() { 
     // $http.get('/api/driver/fleets/').then(function (res) { 
     //  return angular.forEach(res.data, function (item) { 
     //   return $scope.dfleets.push(item); 
     //  }); 
     // }); 
     $scope.dfleets = []; 
     let totalCars = 0; 
     dummyData.forEach(function(fleet){ 
     $scope.dfleets.push(fleet); 
     totalCars+= fleet.cars; 
     }); 
     //alphabetize first? 
     $scope.dfleets.sort(function(a,b){return (a.brand < b.brand) ? -1 : 1;}); 
     //insert your custom default to appear giving it an arbitrary id? 
     $scope.dfleets.unshift({id: "idAll", brand: "All Fleets'", cars: totalCars}); 
     // initialize display if you're using more detailed ng-repeat approach 
    $scope.selectedFleetFromId = {id: "idAll", brand: "All Fleets'", cars: totalCars} 
    }; 

    $scope.handleFleetSelection = function(fleet){ 
     $scope.hideProcessingMessage=false; 
     $scope.processingMessage = "Congratulations, your " + fleet.brand + " representative will contact you soon"; 
    } 

    $scope.handleFleetSelectionFromString = function(fleetIdString){ 
     $scope.selectedFleetFromId = $scope.dfleets.find((fleet) => fleetIdString === fleet.id); 
     $scope.hideProcessingMessage=false; 
     $scope.processingMessage = "Congratulations, your " + $scope.selectedFleetFromId.brand + " representative will contact you soon"; 
    } 


    $scope.showDriversFleets(); 


}) 

我希望我的想法幫助你遠一點,即使它們並不完美。 :)

此前的SO帖子討論了角度選擇框的使用...不完全是您的默認問題,但值得一看。 how to use ng-option to set default value of select element

+0

感謝您提供詳細的解決方案 – NomaD

1

使用NG選項,並選擇元素中添加一個空的默認值的選擇,因爲 -

<select ng-options="..."> 
    <option value="">Select Value</option> 
</select> 

OR

如果要選擇,然後指定集合中的選項 -
Plunker - https://plnkr.co/edit/ApMlLTLOXfJKKutcEuFW?p=preview

angular.module('app', []) 
    .controller('ctrl', function($scope, $http) { 
    var urlBase = 'countries.json'; 
    $scope.register = {}; 
    $scope.register.countryId = "-1"; 
    $scope.register.countries = []; 
    $scope.showDriversFleets = function() { 
     $http.get(urlBase).success(CreateCountryList); 
    } 

    function CreateCountryList(res) { 
     angular.forEach(res, function(item) { 
     $scope.register.countries.push(item); 
     }); 
     $scope.register.countries.insert(0, { 
     "id": "-1", 
     "name": "Select Country" 
     }); 
    } 

    Array.prototype.insert = function(index, item) { 
     this.splice(index, 0, item); 
    }; 
    }) 
+0

謝謝,我想到了選擇的想法,但我怎樣才能添加一個選項'{「id」: - 1,「name」:「所有國家」這不是由http.get請求分配的,但應該默認選擇? – NomaD

+0

我根據您的要求更新了代碼。請看一下。 –

+0

美好而簡單的解決方案! – NomaD