I am facing a challenge with my Angular service that retrieves a list of objects with a composite key comprising two parts. I am struggling to write the bindings in a way that properly re-binds existing data. Below is my current attempt:
angular.module("app", [])
.controller("fooCtrl", function() {
// Data obtained from Angular service / back-end:
this.options = [
{ part1: 3, part2: 101, displayName: "Option 3-101" },
{ part1: 4, part2: 651, displayName: "Option 4-651" },
{ part1: 4, part2: 999, displayName: "Option 4-999" }
];
this.item = { selectedOption: { part1: 4, part2: 651 } };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="app" ng-controller="fooCtrl as vm">
<select ng-options="option.displayName for option in vm.options track by part1 + '-' + part2"
ng-model="vm.item.selectedOption"></select>
<hr>
Debug info:
<pre>{{vm.item | json}}</pre>
</div>
However, the above setup is not functioning as expected: it should be selecting "Option 4-651"
upon loading, but it fails to do so.
Please note that the client-side displayName
field is added to the options, but it does not exist in the selectedOption
during initialization. I am open to modifying the selectedOption
to include the displayName
property without affecting the back-end processing since the server-side DTO does not have a displayName
property.
Crucially, I am seeking a solution without altering the loading process in the JavaScript or changing the structure of options
and selectedOption
. Specifically:
- I understand I could manually reset
this.item
using logic at the end of the controller method to reference the actual entry inoptions
, though this is complicated in real-time scenarios due to asynchronous loading. - I also acknowledge that I could modify both the
selectedOption
and individualoptions
to incorporate a "composite key" as a "single compound key," likepart1and2: "3-101"
, yet this would require addressing the underlying issue rather than directly binding the UI to DTOs from the back-end.
Is there an elegant way to tackle this using a track by
expression in the binding expressions? Alternatively, must I resolve this matter within the controller or service code?