tamita tamita - 4 years ago 129
AngularJS Question

Angularjs function calls order

I have a dropdown list of options, which are shown or not depending on conditions.

<div class="col-sm-9">
<select class="form-control" ng-model="vm.templateType" ng-disabled="vm.status == 'sold' || vm.status == 'return' "ng-options="type.id as type.name for type in vm.templateTypes | filter:vm.isShowableTemplate"></select>
</div>


Here is my controller:

function FormOrderDialogController(tsModulesService, $scope, $q, $http, $uibModalInstance, params, $filter, Requester)

Requester.restGet("/events/" + params.eventId, null, params.serverId).then((data)=>{
vm.event = data;
});

Requester.restGet('/dic/10', null, null, null, true).then((resp) => {
vm.templateTypes = resp;
vm.templateType = vm.templateTypes[0].id;
});

vm.isShowableTemplate = isShowableTemplate;

function isShowableTemplate(templateType) {

switch (templateType.id) {
case 321:
return !!vm.event.info.ticketTemplate;
case 322:
return !!vm.event.info.ticketETemplate;
}
}


By the time isShowableTemplate is called I expect event object to be filled, And the thing is the getEvent function is called twice, once before isShowableTemplate get called, and once after. The problem is event is undefined after the first call and I get an error "Cannot read property 'info' of undefined".
My question is why is it so and what I am doing wrong. I am new to both js and angular, so may be I miss something essential.

Answer Source

Why not remove the function and filter:

function FormOrderDialogController(tsModulesService, $scope, $q, $http, $uibModalInstance, params, $filter, Requester)                              

    Requester.restGet("/events/" + params.eventId, null, params.serverId)
        .then(data => {
            vm.event = data;

            return Requester.restGet('/dic/10', null, null, null, true);
        })
        .then(resp => {
            vm.templateTypes = resp;
            vm.showableTemplateTypes = resp.filter(t => { 
                switch (t.id) {
                    case 321:
                        return !!vm.event.info.ticketTemplate;
                    case 322:
                        return !!vm.event.info.ticketTemplate;
                }

                return false; // or true depending if you want to show the     others.
            });

            vm.templateType = vm.templateTypes[0].id;
        });   
}  

I've combined the two Promises together because you use the vm.event in the second response. By doing it this way, you can always guarantee some value for vm.event.

The html:

<div class="col-sm-9">
    <select class="form-control" ng-model="vm.templateType" ng-disabled="vm.status == 'sold' || vm.status == 'return' "ng-options="type.id as type.name for type in vm.showableTemplateTypes"></select>
</div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download