Custom directive to populate dynamic select box AngularJS

576 views Asked by At

I've got the following controller that basically calls a http get service and assigns the data to a show_data scope variable

.controller('forms_controller', function($scope, Form) {

Form.get().then(function(data){
    $scope.show_data = data;
});


});

The scope.show_data is then pushed to this view ..

<div ng-repeat="(key, value) in show_data | orderBy:'key' " >
<div ng-switch on="value.Type" >
    <div ng-switch-when="attributes" >
        <div ng-repeat="(key2, value2) in value | orderBy:'key' ">

            <div ng-switch-when="Date" >                            
                <label class="item item-input">
                    <span class="input-label">{{value2.Label}}</span>
                    <input identifier="{{value2.Identifier}}" type="date">
                </label>
            </div>

            <div ng-switch-when="Select" >
                <label class="item item-input item-select">
                    <div class="input-label">
                    {{value2.Label}}
                    </div>
                        <select codelist="{{value2.CodeList}}" identifier="{{value2.Identifier}}" >
                    </select>
                </label>
            </div>

        </div>
    </div>
</div>

Which basically checks the data based on the input type and spits out the different form elements based on the data. My problem is I am faced with is with the select box... Each select box has an id [codelist in this case] to the ng-options that should be displayed however, I'd first need to make another http get call to fetch this data before populating the ng-options ...
Please also note that there might be more then one select box per form.

I was thinking of using some kind've custom directive to achieve this?
Any help would be highly appreciated :)
Thank You

1

There are 1 answers

2
wvdz On BEST ANSWER

Your problem is that the server sends you an "incomplete" object. You need to do additional get requests to "complete" your object.

So this is what you should do: in your controller, iterate over your object and do the additional get-requests and store the results in something that you can call in your html with value2.items.

You don't have to wait with setting $scope.show_data untill all the data is fetched. Angular's two-way binding will synchronize the html as soon as the additional info is available.

Something like this should work.

var n = 0;
for (;n < data.length; n += 1) {
    var values = data[n].value
    var i = 0;
    for (;i < values.length; i += 1) {
        // GET based on values[i].CodeList
        $http.get(...)
        .success(function (data2) {
             values[i].items = data2
             // Retrieveable in HTML as value2.items
        });
    }
}