2016-09-29 60 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