Angular.js: Using ng-model for dropdowns within ng-repeat

可紊 提交于 2019-12-04 11:27:45

问题


I'm having a hard time understanding how to use ng-model within ng-repeat. In this context, CargoItems is a list of objects that have a LoadPoint on them. LoadPoint has Id and Text properties.

I want to show the text, bound to the current selection in the dropdown, but I also want to track which Id is selected of course. So I'm not sure how to update both properties with the select bindings, either through an explicit use of tags, or using ng-options which I haven't really figured out yet.

So two questions:

1) how do I properly bind both the text and value from the select list to the Id and Text properties on my CargoItem.LoadPoint? I have a feeling my ng-model might be wrong?

2) how do I use ng-options to default to the selected value? I figured this out writing my own option tag, but I'd like to use ng-options if possible.

<div ng-repeat="cargoItem in cargo.CargoItems">
    <span>Selected Load Point: {{cargo.LoadPoint.Text}}</span> 
    <select ng-model="cargoItem.LoadPoint" ng-options="loadPoint.Id as loadPoint.Text for loadPoint in LoadPoints"></select>
</div>

Thanks in advance!


回答1:


  1. Bind to the entire object reference instead of using the 'Id' property (loadPoint.Id). To do that, just change the ng-options and remove the loadPoint.Id as part:

    <select ng-model="cargoItem.LoadPoint" ng-options="loadPoint.Text for loadPoint in LoadPoints"></select>
    
  2. If you use the above approach and the correct reference to the LoadPoints object, Angular will do that for you automatically. Here's an example on how to use a direct LoadPoints object reference:

    $scope.LoadPoints = [{ Id: '1', Text: 'loadPointA' },{ Id: '2', Text: 'loadPointB' }];        
    $scope.cargo = {
        CargoItems: [{
            LoadPoint: $scope.LoadPoints[0]
        }, {
            LoadPoint: $scope.LoadPoints[1]
        }]
    };
    

    Using this approach, cargoItem.LoadPoint (the ngModel) will always hold a reference to the entire LoadPoints object (i.e. { Id: '1', Text: 'loadPointA' }), and not only its Id (i.e. '1').

jsFiddle: http://jsfiddle.net/bmleite/baRb5/



来源:https://stackoverflow.com/questions/14749699/angular-js-using-ng-model-for-dropdowns-within-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!