通过在angualrjs中使用“track by”来选择下拉列表无法正常工作的默认值

时间:2016-11-25 12:14:00

标签: javascript angularjs javascript-events angularjs-scope

我正在使用track by来避免附加到::string的奇怪值value,但是当我默认选择下拉列表时,下拉列表未被选中.. 这是我的傻瓜

Example Plunker

2 个答案:

答案 0 :(得分:1)



(function(angular) {
  'use strict';
angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
     selectedOption: '2' //This sets the default value of the select in the ui
     };
 }]);
})(window.angular);

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-with-default-values-production</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
  <script src="script.js"></script>
</head>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="mySelect">Make a choice:</label>
   
      
    <select ng-model="data.selectedOption"> 
       <option ng-repeat="option in data.availableOptions track by option.id" value="{{option.id}}">{{ option.name}}</option> 
    </select>
  </form>
  <hr>
  <tt>option = {{data.selectedOption}}</tt><br/>
</div>
</body>
</html>
&#13;
&#13;
&#13;

演示的工作片段

请更改您的<select>标记,如下所示

<select ng-model="data.selectedOption"> 
   <option ng-repeat="option in data.availableOptions track by option.id" value="{{option.id}}">{{ option.name}}</option> 
</select>

答案 1 :(得分:1)

这将有效:

<select name="mySelect" id="mySelect" ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"></select>

$scope.data = { availableOptions: [ {id: 1, name: 'Option A'}, {id: 2, name: 'Option B'}, {id: 3, name: 'Option C'} ], selectedOption: {id: 2, name: 'Option B'} };

http://plnkr.co/edit/yOPa3hb2nSgkpOfu8NbT?p=preview