2016-09-29 55 views
0

我很努力地讓「選中」與'track by'一起爲Angular select元素工作。我有以下選擇:角度選擇'track by'重置選中

<select id="licenseType" ng-model="selectedLicense" 
      ng-options="key for (key, value) in licenseMap track by key" 
      ng-change="doUpdate()"> 
    </select> 

這個JS:

$scope.selectedLicense = $scope.licenseMap["Please Select"]; 

以上的js工作,當我得到「者皆軌道」擺脫 - 最初的選擇被預置。通過「按鍵確定」,預選是空白的。我需要'按鍵'來獲取選定的值,這是目前唯一的工作。我曾嘗試以下德組合迄今沒有奏效:

/* 
var license = document.getElementById('licenseType'); 
license.options.selectedIndex = 1; 
license.options[license.options.selectedIndex].selected = true; 
$("#licenseType").val("Please Select"); 
$('#licenseType').children('option[value="1"]').attr('selected', true);  
*/ 

我最欣賞一些幫助這裏得到它的工作。謝謝。

+0

你爲什麼需要跟蹤?在doUpdate()中,您應該能夠訪問selectedLicense並在那裏獲取選定的值。 – Dylan

+0

@ user2917629:我的select是一個多維數組,並且track-by是獲取所選鍵的唯一技巧,否則我返回數組 – user2917629

回答

2

做這樣的事情:http://codepen.io/alex06/pen/XjarJd

div(data-ng-app="app") 
div(ng-controller="appController") 
    select.form-control(ng-model="selectedItem", ng-options="option.value as option.name for option in typeOptions track by option.value" ng-init="selectedItem=typeOptions[0]") 


(function(){ 
    'use strict' 
    angular 
    .module('app', []) 
    .controller('appController', ['$scope', function($scope){ 

     $scope.typeOptions = [ 
     { name: 'Feature', value: 'feature' }, 
     { name: 'Bug', value: 'bug' }, 
     { name: 'Enhancement', value: 'enhancement' } 
     ]; 
    }]) 
})() 

的例子在玉製成的,但它是幾乎相同syntax.By的方式,如果你仍然想用一個對象而不是數組,你也可以工作這樣做:

<!DOCTYPE html> 
<html ng-app="app"> 

<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js">    </script> 
    <link rel="stylesheet" href="style.css" /> 
    <script type="text/javascript"> 
    angular.module('app', []) 
     .controller('IndexCtrl', ['$scope', function($scope) { 
     $scope.types = { 
      1: "value1", 
      2: "value2", 
      5: "value3" 
     }; 
     }]); 
    </script> 
    </head> 
    <body ng-app="app" ng-controller="IndexCtrl"> 
    <select ng-model="type" ng-options="k as v for (k, v) in types"> 
     <option value="">Please select</option> 
    </select> 
    </body> 

</html> 
+0

我剛試過ng-init =「selectedItem = typeOptions [0]」,我自己的數據參考,但仍然沒有運氣。 – user2917629

+0

請注意,我上傳的示例使用的是數組,我相信您使用的是普通對象。這就是爲什麼我上傳了一個數組,然後是另一個對象,如果你只需要選擇一個沒有值的默認選項,使用我的第二個例子。 – AlexP

+0

我試過使用以及ng-init,但它們不會預先選擇,我猜測是因爲我正在處理多維數組。 – user2917629