Pregunta

I have the following code:

<select class="form-control" data-ng-model="form.ProtocolId" data-ng-options="protocol.ProtocolId as protocol.Name for protocol in protocols" required />

Where a protocol has this structure:

[{ "ProtocolId": 1, "Name": "Protocol 1", "Description": "A description for protocol 1" }]

In $scope.form I am setting the ProtocolId, which is what I need to submit the form. But I would like to show the description of the Protocol to the user when they select it. Sort of like {{selectedProtocol.Description}}. Except I don't have a selectedProtocol as I'm only selecting the id.

Is there a way to get the actual selected Protocol here? I could write a method to track the change of a selected Protocol and then in my controller set the form.ProtocolId, but I wonder if there is a simpler way...

¿Fue útil?

Solución

I tend not to use the ng-options directive for select just because there is usually something else I want to do as well...

<select class="form-control" ng-model="form.protocol" required>
    <option ng-repeat="protocol in protocols" value="protocol">{{protocol.Name}}</option>
</select>
<div ng-show="form.protocol.Description">{{form.protocol.Description}}</div>

Now when a selection is made form.protocol is set with the JS object for the selected protocol. You can manipulate it later to just send the form.protocol.ProtocolID upon submit.

Otros consejos

So I marked the ngRepeat option as an answer, but I ended up not using it for several reasons: primary being that my list values were not populated correctly in my form with angularjs due to my model structure. What DID work however was this:

<select class="form-control" data-ng-model="form.PrimaryProtocolId" data-ng-options="protocol.ProtocolId as primaryDisplayName(protocol) for protocol in primaryprotocols" required />

Where primaryDisplayName() is a method on my $scope that gives me the format I need:

$scope.primaryProtocolName = function(protocol) {
    return protocol.Name + " (" + protocol.ProtocolType.Name + ")";
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top