1

我想知道在 ng-options 指令中建议在哪些情况下使用track by over select ?

在这里,我们有两个选择:

<select ng-options="item.id as item.name for item in items" ng-model="selectedItemSA">

<select ng-options="item.name for item in items track by item.id" ng-model="selectedItemTB">

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-init="items = [{id: 1, name: 'item1'}, {id: 2, name: 'item2'}]">
  
    <div>
      <h2>Using select as</h2>
      <select ng-options="item.id as item.name for item in items" ng-model="selectedItemSA">
      </select>
      <button ng-click="selectedItemSA = 2;">Select item 2</button>
    </div>
    
    <div>
      <h2>Using track by</h2>      
      <select ng-options="item.name for item in items track by item.id" ng-model="selectedItemTB">
      </select>
      <button ng-click="selectedItemTB = {id: 2, name: 'item2'};">Select item 2</button>
    </div>  
        
  </div>
</div>

我们可以看到html结果是一样的:

  <div>
    <h2>Using select as</h2>
    <select ng-options="item.id as item.name for item in items" ng-model="selectedItemSA" class="ng-pristine ng-untouched ng-valid ng-empty">
      <option value="?" selected="selected"></option>
      <option label="item1" value="number:1">item1</option>
      <option label="item2" value="number:2">item2</option>
    </select>
    <button ng-click="selectedItemSA = 2;">Select item 2</button>
  </div>

  <div>
    <h2>Using track by</h2>
    <select ng-options="item.name for item in items track by item.id" ng-model="selectedItemTB" class="ng-pristine ng-untouched ng-valid ng-empty">
      <option value="?" selected="selected"></option>
      <option label="item1" value="1">item1</option>
      <option label="item2" value="2">item2</option>
    </select>
    <button ng-click="selectedItemTB = {id: 2, name: 'item2'};">Select item 2</button>
  </div>

要像我们必须做的那样使用 select 选择一个项目:

selectedItemSA = 2;

要选择带有track by的项目,我们必须执行以下操作:

selectedItemTB = {id: 2, name: 'item2'};

大多数时候,我只能访问项目 ID,或者只是使用项目 ID 比使用整个对象更容易。所以我总是更喜欢使用select as over track by

您知道在哪种情况下跟踪是更可取的选择吗?

4

0 回答 0