kirgy kirgy - 1 month ago 29
AngularJS Question

Angular select, ng-init with dynamic value

I'm trying to get a select box working in Angular. The problem I'm experiencing is to do with ng-init and setting it's default value from an object which is created during runtime. Heres my code:

<select
ng-model="settings.editing.panel.data.production_company"
ng-change="settings.editing.panel.data.production_company = selectValue"
ng-init="selectValue = settings.editing.panel.data.production_company"
>
<option
ng-repeat="(key, value) in lists.production_companies"
value="{{key}}"
ng-selected="{{selectValue}}"
>
{{value}}
</option>
</select>


"lists.production_companies" is a simple key-value array of names, populated during initial page render, updated by ajax.

The object "settings.editing.panel.data" starts its life as NULL, but later is loaded with a correctly formatted object which contains the property "production_company".

I have found setting ng-init to something like "ng-init="selectValue = 3" works fine. Setting a $scope.test = 3, then setting "ng-init="selectValue = test" works fine too.

However, my dynamic value does not work. How can I use my dynamically created object to set the value of this select box during runtime with the set-up I have?

Answer

In my circumstances I was able to change my backends data format to set an object like:

{"id": 1, "name":"prod comp 1"} 

and then change my select model accordingly. In hindsight I needed this for the ID anyway.

<select 
    ng-model="settings.editing.panel.data.production_company"
>
    <option 
        ng-repeat="option in settings.lists.production_companies" 
        value="{{option.id}}"
        ng-selected="{{option.id}} == settings.editing.panel.data.production_company"
    >
        {{option.name}}
    </option>
</select>