簡體   English   中英

如何在單個AngularJS上下文中為多個選擇元素設置選擇的值

[英]How to set the selected value for multiple select elements in a single AngularJS context

我嘗試在單個上下文中的AngularJS頁面上創建多個選擇元素。 names是可用名稱對象的數組, cores是具有可用核心的數組。 對於每個名稱,我想提供一個可用的內核列表。 這可以正常工作,但是我無法預先選擇當前選擇的核心。 那個存儲在name.core中。

<ul>                                                                      
  <li ng-repeat='name in names'>                                        
    {{ name.name }} - {{ name._url }} <span ng-click='delete_name(name)'>[x]</span>    
    <select ng-model='?'                                       
      ng-options='core.id as core.instance for core in cores'           
      ng-change='coreChanged(name, ?)'>                       
      <option value=''>No core assigned</option>                        
    </select>                                                             
  </li>                                                                 
 </ul>         

我對AngularJS還是很陌生,所以如果其他結構或其他控制器,范圍,...更合適,我歡迎您提出建議。

更新: ng-model='name.core'提議的ng-model='name.core'不起作用,可能是因為name.core不是cores數組中的實例。 我嘗試了ng-model='name.core.id'但這導致每個下拉列表都具有相同(錯誤)的選擇。

這對我來說很好:

<ul>                                                                      
    <li ng-repeat='name in names'>                                        
        {{ name.name }} - {{ name._url }} <span ng-click='delete_name(name)'>[x]</span>    
        <select ng-model='name.core'                                       
        ng-options='core.id as core.instance for core in cores'           
        ng-change='coreChanged(name)'>                       
            <option value=''>No core assigned</option>
        </select>                                                             
    </li>                                                                 
</ul>

仔細檢查您的視圖與模型的對應關系。 我的范圍變量如下所示:

.controller('MyController', function($scope){
  $scope.names = [
    { name: 'Marc', url: 'http://www.example.com/one', core: "1"  },
    { name: 'Achim', url: 'http://www.example.com/two', core: "2"  },
    { name: 'Jenny', url: 'http://www.example.com/three', core: "3" }
  ];

  $scope.cores = [
    { id: '1', instance: 'First' },
    { id: '2', instance: 'Second' },
    { id: '3', instance: 'Third' }
  ];

  $scope.coreChanged = function(name){
    console.log(name);
  }
});

工作柱塞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM