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

时间:2016-04-13 11:34:49

标签: javascript jquery angularjs

我想在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呈现之前确保加载数据?

3 个答案:

答案 0 :(得分:6)

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

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

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

routeProvider

答案 1 :(得分:1)

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

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

    });

答案 2 :(得分:0)

您需要以某种方式将您的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(如果可以接受的话,只在$ rootScope上设置)。希望它有所帮助!