How to prevent screen flickering with AngularJs?

流过昼夜 提交于 2019-12-23 04:47:57

问题


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;
            });
        }
    }
}])

回答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




回答2:


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?




回答3:


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
    })


来源:https://stackoverflow.com/questions/21672902/how-to-prevent-screen-flickering-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!