0

I have an Angular1.0.7 webapp. I have a select with ng-options element like:

<select bs-select data-width="180px" ng-model="searching.duration" ng-options="duration as duration.name for duration in durations">
            <option value="">{{'DURATION' | translate}}</option>
        </select>   

and duratios is an array of object like:

durations= [{"id":11,"name":"DURATION_1_DAY","value":1},{"id":12,"name":"DURATION_2_DAYS","value":2}, ...]

As you can see in the select, I would like to assign the complete object to the model like: duration= {"id":11,"name":"DURATION_1_DAY","value":1}

when I select different options the model is assigned correctly. However, when the model has a initial value the select is not properly initialized with the right value.

Rober
  • 5,868
  • 17
  • 58
  • 110
  • can you share your controller code where you are assigning – Negi Rox Oct 10 '18 at 10:08
  • It´s not easy to explain. When I select an option the value is stored in the model. This select is inside a form with a submit button. Each time I click on the submit button the model is stored in session. I can navigate to another page and back to this one, so on that case, the model is filled with the value in session and the object is displayed correctly, but the select is not initialized right. I just set and get the searching object like: sessionStorage.setItem('searching', JSON.stringify($scope.searching)); and $scope.searching = JSON.parse(sessionStorage.getItem('searching')); – Rober Oct 10 '18 at 10:59
  • it should be $scope.searching.duration? – Negi Rox Oct 10 '18 at 11:17
  • 1
    Is there a reason you're using Angular 1.0.7? Switching to ~1.2.0+ would give you access to `track by`, which might resolve this: `ng-options="duration as duration.name for duration in durations track by duration.id"` – Dan Oct 10 '18 at 14:22
  • track by should work, if it is not accessible you will probably obliged to update duration in object manually before showing select, so it is exactly same as in options. – Petr Averyanov Oct 10 '18 at 15:40
  • @sh0ber yes there is a reason. We have a big webapp and as you know a migration like this is not that easy. At this moment I don´t have the time neither resources to migrate. That´s why I specify the problem is in this version. – Rober Oct 10 '18 at 16:17
  • @Rober, try `angular.toJson(obj)` instead of `JSON.stringify`. https://stackoverflow.com/questions/18826320/what-is-the-hashkey-added-to-my-json-stringify-result – Dan Oct 10 '18 at 16:58
  • I will check and let you know. – Rober Oct 11 '18 at 07:15

0 Answers0