1

I have an HTML form that makes use of a select element. The options of the select element are populated via an API call. I am finding that at times the page appears to be done loading but the select element is not yet populated. I am looking for a way to disable the page or indicate that it is not finished loading until the select element is populated from the API.

I have a single controller that handles the population of the select element as well as the Submit button click event which submits the form data to the back-end API. Below is my Angular and a snippet of the HTML that contais the select element.

HTML

<select ng-model="self.form.UserName" 
    ng-options="user.Name as user.Name for user in self.userList" 
    ng-required="true">
    <option value="">- Choose User -</option>
</select>

Angular

<script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.controller('myAppController', function ($scope, $http) {
        var self = this;
        self.userList= [];

        $http({
            method: 'GET',
            url: 'https://myApi.local/api/users/getAllUsers',
            headers : {
                'Content-Type': 'application/json'
            }
        }).then(function(result) {
            self.userList= result.data;
        }, function (error) {
            console.log(error);
        });

        self.submitFormData = function() {
            // form data submission handled  here
        }
    });
</script>

Would this be a good use of ng-cloak to hide the entire page?

webworm
  • 10,587
  • 33
  • 120
  • 217
  • 1
    a common way to handle this is to use `ng-if` on the select box, e.g. `ng-if="self.userList"`. This would cause the select box to not be rendered until there is data to show in the list. you could also use `ng-if="!self.userList"` to display a loading banner or progress bar. However, for this to work, you would want to remove `self.userList = [];` from your controller; which isn't strictly required anyway. – Claies Mar 03 '17 at 19:44

1 Answers1

2

I would lay my call out more like this to get the finally block. I would have a spinner on the page show and block the user from touching anything behind it while it was going. This way, the user knows the page is still loading and cannot interact with the unpopulated drop-down.

    $scope.showSpinner = true;
    $http({
        method: 'GET',
        url: 'https://myApi.local/api/users/getAllUsers',
        headers : {
            'Content-Type': 'application/json'
        }
    }).then(function(result) {
        self.userList= result.data;
    }).error(function (error) {
        console.log(error);
    }).finally(function(){
    $scope.showSpinner = false;
    });