0

I've multiple directives which fetch their data from the database. In one case I have all the directives in one screen. This means that when the screen is loading each dropdown/field is filled one by one: first you see field A being field, then field B get's his value, then field C, etc. etc. I don't want this, I want that all the data is displayed at once.

How can I achieve this?

Here is one example of a directive. I have about 10 of these directives.

app.directive("environmentDropdown", ['EnvironmentService', function (EnvironmentService) {
    return {
        restrict: 'E',
        template: '<select class="form-control" data-ng-options="e.Id as e.Name for e in environments"></select>',
        scope: {
        },
        replace:true,
        link: function (scope, element, attributes) {
            EnvironmentService.getEnvironments().then(function (response) {
                scope.environments = response;
            });
        }
    }
}])
Chen-Tsu Lin
  • 22,876
  • 16
  • 53
  • 63
Martijn
  • 24,441
  • 60
  • 174
  • 261

3 Answers3

1

For that purpose I am using ng Cloak

It makes the elements, after which you place the tag invisible until the whole page is loaded

CodeFanatic
  • 11,434
  • 1
  • 20
  • 38
  • 1
    In all my directives I have added `ng-cloak` into the template. When loading my page, I still see all the fields getting filled one by one, instead of all at once. – Martijn Feb 10 '14 at 09:58
  • did you add an !important after the ng cloak display:none css rule? – CodeFanatic Feb 10 '14 at 10:04
  • Yes, I've copied the css class from the documentation, which included the `!important` part.. – Martijn Feb 10 '14 at 10:18
1

You could fetch all data before the view is loaded:

 app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
    when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
        myData: function($q,$http){
            var deffered = $q.defer();

                // make your http request here 
                // store the result in a shared service

            return deffered.promise;
        }
    }}).
    otherwise({redirectTo: '/'});
}]);

myData could then be injected where needed, containing the data.

See also: $http request before AngularJS app initialises?

Community
  • 1
  • 1
Wottensprels
  • 3,307
  • 2
  • 29
  • 38
0

Since you've not told us how your directives retrieve data, I'll assume you use $http requests.

You can do something like this:

  var promises = []
  for (var i = 0; i < requests.length; i++) {
    var req = requests[i];
    promises.push( $http.post(url, req) )
  }

  $q.all(promises)
    .then(function (data) {
      $scope.fields = data
    })
domokun
  • 3,013
  • 3
  • 29
  • 55