角度选择'track by'重置选中

时间:2016-09-29 21:30:44

标签: angularjs select angularjs-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);     
*/

我将非常感谢帮助它实现这一目标。谢谢。

1 个答案:

答案 0 :(得分: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' }
       ];
    }])
})()

这个例子是用jade制作的,但它的语法几乎相同。顺便说一句,如果你仍想使用对象而不是数组,你也可以这样做:

<!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>