角度选择'track by'重置所选位置



我正在努力让"selected"与'track by'为Angular选择元素工作。我有如下选择:

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

with this js:

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

上面的js工作时,我摆脱了'track by key' -初始选择得到预设。有了"按键跟踪",预选是空白的。我需要"按键跟踪"到位,以获得选定的值,这是迄今为止唯一的工作。到目前为止,我已经尝试了以下组合,但都不起作用:

/*
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);     
*/

我将非常感谢你在这里帮助它工作。谢谢你。

做如下操作: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>

最新更新