繁体   English   中英

在页面加载之前加载Angular JS数据

[英]Angular JS Data loading Before Page Loading

我想在AngularJS Page Load之前加载数据。 我在Angualr上也使用bootstrap和JQuery。 主要问题是我在页面上有表格,并使用JQuery进行分页和其他过滤器,包括响应性。

现在发生了什么,该页面加载了所有JQuery,后来我的数据出现在页面上,没有什么像分页等。我做了以下解决方法:

 <script>
      $(function () {
        //  document.body.style.overflow = 'hidden';
          setTimeout(
                  function() 

                      $('#example1').DataTable({
                          "paging": true,
                          "lengthChange": false,
                          "searching": true,
                          "ordering": true,
                          "info": true,
                          "autoWidth": true,
                          "scrollX": true
                        });
                  }, 500);

      });
    </script>

我添加了手动延迟等待JQuery,以便该页面之前加载其数据。

任何人都可以告诉好的解决方案,如何确保在页面HTML呈现之前加载数据?

我强烈建议不要使用jQuery进行分页。 还有其他解决方案可以让Angular魔法为你工作,比如ui-grid,smart-table等。这些都需要你很少的努力。

如果你真的想继续沿着这条道路前进,那么你可以通过$routeProvider.when的决心获得你想要的东西。 当请求路由时,解析块将首先运行任何promise,并在转到该路由之前等待它们解析。 Resolve还可以将该数据传递到路径的控制器中:

.when('/route', {
    ...,
    resolve: {
        dataYouWant: function(DataGettingService) {
            return DataGettingService.get();
        }
    }
})

routeProvider

这只是一种可能的解决方案。 您也可以使用指令而不是控制器

angular
    .module('app', [])
    .factory('repository', function ($http) {
        var loadData = function () {
            return $http... ;//make http call here and return the promise
        };

        return {
            loadData: loadData
        };
    })
    .controller('myCtrl', function (repository) {
        repository.loadData().then(function(data) {
            // use loaded data here
            $('#example1').DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": true,
                "scrollX": true
            });
        });

    });

您需要以某种方式将您的jQuery代码与Angular绑定。 这是指令尝试。

app.directive('jqueryCallDirective' , function() {
   return {
        link: function(scope, element, attrs) {
            element.DataTable({
                "paging": true,
                 ...
            });
        }
   }
});

然后对元素使用ng-if延迟渲染:

<div id="example1" ng-if="hasData" jquery-call-directive> ... </div>

然后在适当的范围$scope.hasData = true适当的时间设置$scope.hasData = true (如果可以接受的话,只在$ rootScope上设置)。 希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM