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!
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>
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With