AngularJS ngTable延迟AJAX的数据显示 [英] AngularJS ngTable delays display of ajax data

查看:551
本文介绍了AngularJS ngTable延迟AJAX的数据显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我挣扎使用 ngTable 的细微之处。我经历了 ngTable阿贾克斯演示,并试图效仿合理地;但是,我需要从哪里 ngTable阿贾克斯演示定义了部分偏离< A HREF =htt​​p://docs.angularjs.org/api/ngResource/service/%24resource相对=nofollow> ngResource 内嵌控制器。

I am struggling with the finer points of using ngTable. I went through the ngTable ajax demo and tried to follow the example as reasonably as possible; however, I need to deviate from the part where the ngTable ajax demo defines an ngResource inline with the Controller.

我成功地建立了一个 ngTable ,提供的 ngTable过滤器;我的web应用程序是 这里 (也看到 plunker )。这是一个ngTable其中:

I successfully built an ngTable with ngTable filters; My webapp is here (also see the plunker). This is an ngTable which:

  • Loads data from a json REST service
  • Builds the ngTable from the json data
  • Sorts
  • Filters

借助 JSON REST服务正确加载,并且过滤器的工作。不过,我的问题是,直到我输入一些东西在Filter字段中(请参见前<表是空白/ A>和下面截图)之后。

The json REST service loads correctly, and the filters work. However, my problem is that the table is blank until I type something in the Filter field (see the before and after screenshots below).

问题存在着我已经尝试了所有的浏览器:

The problem exists with all browsers I have tried:

  • 在火狐27.0.1(Windows Vista的)
  • 在Chrome浏览器版本33.0.1750.146(Windows Vista的)
  • 在Chrome浏览器版本32.0.1700.123(Linux的 - 的Debian 7.0喘息)

我知道web应用程序在互联网打破爆9 ...我不知道为什么,但我真的不关心IE浏览器;这个Web应用程序不会成为一个公共的Web服务。

I know the webapp is broken in Internet Exploder 9... I don't know why, but I really don't care about IE; this webapp is not going to be a public web service.

  • 如何使表填充我第一次加载我的web应用程序(没有在过滤器中键入什么箱)?
  • 这是为什么破了吧?
  • How do I make the table populate the first time I load my webapp (without typing anything in the filter boxes)?
  • Why is this broken now?

注意的:源$ C ​​$ C在页​​面的底部......我建了一个 plunker 吧。

Note: The source code is at the bottom of the page... I built a plunker for it.


完备注

注意1 <子>的眼尖的读者可能会注意到,我使用 []] 在我的 AngularJS 的形式,而不是默认卷曲-brace分隔符。我这样做是因为我使用​​瓶,提供的神社(这也需要双大括号为它的模板引擎)。


屏幕截图

Note 1Sharp-eyed readers may notice that I'm using [[ and ]] in my AngularJS form instead of the default curly-brace delimiters. I did this because I'm using Flask with Jinja (which also needs double curly-braces for its templating engine)..


Screen shots

BEFORE:页面是当我​​打开空白的:

空白ngTable

后:但是,如果我输入任何字符在过滤器中, ngTable 显示数据的:

AFTER: However, if I type any character in the filters, the ngTable displays the data:

ngTable带过滤器


<script type="text/javascript">

    "use strict";
    // Set up an ngResource service to make HTTP GET / POST / DELETE calls
    var Api = angular.module("api_main", ["ngResource"]);
    Api.factory("restDemo", function ($resource) {
        // http://www.masnun.com/2013/08/28/rest-access-in-angularjs-using-ngresource.html
        return $resource("http://demo.pennington.net/demo/api/v1/data01", {}, {});
    });

    // Loosely based on this ngTable demo...
    //       http://bazalt-cms.com/ng-table/example/6
    var App2 = angular.module('taskTable', ['ngRoute', 'api_main', 
        'ngTable']);
    // Need to change AngularJS symbols when using flask + Jinja
    App2.config(function($interpolateProvider) {
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');
    });

    App2.controller('tableCntl', function($scope, $filter, restDemo, ngTableParams) {


        var data = restDemo.query(); // HTTP GET for REST service


        // Set up task table parameters
        /* Lib3d's fix (i.e. data.$promise) is below */
        data.$promise.then(function (data) {
            /* the data is here, work with it */
            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 10,          // count per page
                total: data.length,
                sorting: {
                    Column01: 'asc',
                    Column02: 'asc',
                    Column03: 'asc'
                },
                filter: {
                    Column01: "",
                    Column02: "",
                    Column03: "",
                }
            }, {
                getData: function($defer, params) {

                    // Filtering
                    var orderedData = params.filter() ?
                           $filter('filter')(data, params.filter()) :
                           data;

                    // Sorting
                    orderedData = params.sorting() ?
                        $filter('orderBy')(orderedData, params.orderBy()) :
                        orderedData;
                   $defer.resolve(orderedData.slice((params.page() - 1) * params.count(),  params.page() * params.count()));

                    /* set total for recalc pagination */
                    params.total(orderedData.length);

                    // This shouldn't be required, but keeping here in case
                    //if(!$scope.$$phase) {
                    //    $scope.$apply();
                    //}
                }
            });
        });
    });
</script>


破碎的演示源$ C ​​$ C

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/pure-min.css">
    <link rel="stylesheet" href="//cdn.jsdelivr.net/angular.ngtable/0.3.1/ng-table.css">
    <!--
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
    -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      body {
        padding-top: 30px; /* 30px pad at the top of screen */
      }
    </style>
    <!-- Fix up title -->
    <title>DATA DEMO</title>
  </head>
  <body>
    <div class="pure-g">
    </div>
    <!-- Static navbar -->
    <div class="pure-g">
      <div id="menu" class="pure-u">
        <div class="pure-menu pure-menu-horizontal pure-menu-open">
          <ul>
            <li><a href="#">Add Demo</a></li>
            <li class="active"><a href="#">List Demo</a></li>
            <li><a href="#">List Projects</a></li>
            <li>
                <a href="/login">Login</a>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </div>
    <!--- insert stuff here -->
  <div id="Tasks" ng-app="taskTable" ng-controller="tableCntl">
    <p><strong>Filter:</strong> [[tableParams.filter()|json]]
    <table ng-table="tableParams" show-filter="true" class="table">
        <tbody>
          <tr ng-repeat="words in $data">
              <td data-title="'Column01'" sortable="Column01" filter="{'Column01': 'text'}">
                  [[words.Column01]]
              </td>
              <td data-title="'Column02'" sortable="Column02" filter="{'Column02': 'text'}">
                  [[words.Column02]]
              </td>
              <td data-title="'Column03'" sortable="Column03" filter="{'Column03': 'text'}">
                  [[words.Column03]]
              </td>
          </tr>
        </tbody>
    </table>
  </div>
  </body>
  <!-- insert JS at the bottom of the page -->
  <footer>
    <!-- all flash messages are processed here -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-route.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-resource.min.js"></script>
    <script type="text/javascript" src="//cdn.jsdelivr.net/angular.ngtable/0.3.1/ng-table.js"></script>
    <!--
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
    -->

    <script type="text/javascript">

        "use strict";
        // Set up an ngResource service to make HTTP GET / POST / DELETE calls
        var Api = angular.module("api_main", ["ngResource"]);
        Api.factory("restDemo", function ($resource) {
            // http://www.masnun.com/2013/08/28/rest-access-in-angularjs-using-ngresource.html
            return $resource("http://demo.pennington.net/demo/api/v1/data01", {}, {});
        });

        // Loosely based on this ngTable demo...
        //       http://bazalt-cms.com/ng-table/example/6
        var App2 = angular.module('taskTable', ['ngRoute', 'api_main', 
            'ngTable']);
        // Need to change AngularJS symbols when using flask + Jinja
        App2.config(function($interpolateProvider) {
            $interpolateProvider.startSymbol('[[');
            $interpolateProvider.endSymbol(']]');
        });

        App2.controller('tableCntl', function($scope, $filter, restDemo, ngTableParams) {


            var data = restDemo.query(); // HTTP GET for REST service
            // Set up task table parameters
            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 10,          // count per page
                total: data.length,
                sorting: {
                    Column01: 'asc',
                    Column02: 'asc',
                    Column03: 'asc'
                },
                filter: {
                    Column01: "",
                    Column02: "",
                    Column03: "",
                }
            }, {
                getData: function($defer, params) {
                    // use build-in angular filter
                    var orderedData = params.filter() ?
                           $filter('filter')(data, params.filter()) :
                           data;

                    //sorting
                    orderedData = params.sorting() ?
                        $filter('orderBy')(orderedData, params.orderBy()) :
                        orderedData;

                    // store filtered data as $scope.words
                    $scope.words = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
                    params.total(orderedData.length); // set total for recalc pagination
                    $defer.resolve($scope.words);
                    $defer.resolve(data.result);
                }
            });
        });
    </script>
    <!-- Custom footer content here -->

  </footer>
</html>


的数据(我会删除演示 JSON REST服务的问题后,在回答)的:


The data (I will delete the demo json REST service after the question is answered):

[{"Column02": "shines", "Column03": "paycheck", "Column01": "days"}, 
 {"Column02": "erg", "Column03": "gag", "Column01": "emotion's"}, 
 {"Column02": "Chris", "Column03": "Poznan's", "Column01": "treasure's"}, 
 {"Column02": "presentiments", "Column03": "Austerlitz's", "Column01": "suppression's"}, 
 {"Column02": "leopards", "Column03": "slosh's", "Column01": "upturned"}, 
 {"Column02": "uncaring", "Column03": "cosmetics", "Column01": "symmetry"}, 
 {"Column02": "guesser's", "Column03": "lapped", "Column01": "retrogressed"},
 {"Column02": "Kurd", "Column03": "wryest", "Column01": "cicadas"}, 
 {"Column02": "cantered", "Column03": "encrustation's", "Column01": "beyond"}, 
 {"Column02": "flybys", "Column03": "poesying", "Column01": "physician's"}, 
 {"Column02": "fun", "Column03": "Delaware's", "Column01": "destructiveness"}, 
 {"Column02": "scramblers", "Column03": "gestates", "Column01": "acoustics"}, 
 {"Column02": "redesigning", "Column03": "cubits", "Column01": "Enterprise"}, 
 {"Column02": "phonograph's", "Column03": "haloed", "Column01": "upsurge"}, 
 {"Column02": "Michelson", "Column03": "Pansy", "Column01": "McCoys"}, 
 {"Column02": "adieu", "Column03": "Dido", "Column01": "ligaturing"}, 
 {"Column02": "osprey's", "Column03": "expressiveness's", "Column01": "Starr"}, 
 {"Column02": "patent's", "Column03": "therapeutically", "Column01": "brasher"}, 
 {"Column02": "enfranchise", "Column03": "idolized", "Column01": "criticized"}, 
 {"Column02": "Angel", "Column03": "wryest", "Column01": "drum"}, 
 {"Column02": "overstaying", "Column03": "tranquillized", "Column01": "alacrity"}, 
 {"Column02": "underachievers", "Column03": "minority", "Column01": "Brigham's"}, 
 {"Column02": "lobotomy's", "Column03": "filament's", "Column01": "scoldings"}, 
 {"Column02": "original", "Column03": "muskmelon's", "Column01": "financially"}, 
 {"Column02": "flagon's", "Column03": "vapidness", "Column01": "Klaus's"}, 
 {"Column02": "dhotis", "Column03": "fleeter", "Column01": "jugulars"}, 
 {"Column02": "shanty", "Column03": "profiteer's", "Column01": "disbelief"}, 
 {"Column02": "bureaucracies", "Column03": "flashier", "Column01": "refrigerating"}, 
 {"Column02": "betrayal's", "Column03": "hindquarters", "Column01": "faze"}, 
 {"Column02": "Poland", "Column03": "cobbler", "Column01": "kidnaped"}]


我用...

  • Yahoo PureCSS version 0.4.2
  • jQuery version 2.0.3
  • AngularJS version 1.2.14Note 1

我已经尝试过什么

所有这些事情似乎对这个问题的影响:

None of these things seemed to have an effect on the problem:

  • 删除的jQuery
  • 删除雅虎PureCSS
  • ngTable
  • 更改默认值过滤器
  • 删除从页面的所有其他JavaScript(这实际上有同一页面上的多个 AngularJS 控制器,但删除了所有其他在希望这只是一个简单的脚本冲突。
  • 在几个实验的假设 - 我 - 修改 - 这的(读:抓住救命稻草),在AngularJS控制器,它构建ngTable
  • 在尝试使用,而不是在我的过滤器空字符串作为的由桑德埃利亚斯
  • 建议
  • Remove jQuery
  • Remove Yahoo PureCSS
  • Change default values on the ngTable Filters
  • Remove all other javascript from the page (this actually had multiple AngularJS controllers on the same page, but removed all others in hopes that it was just a simple script conflict.
  • Several experimental what-if-I-modify-this (read: grasping at straws) in the AngularJS controller which builds the ngTable.
  • Tried using null instead of empty strings in my filter, as suggested by Sander Elias

如果我内嵌在&LT JSON数据;脚本&GT; 块,而不是使一个ajax的 JSON REST服务打电话,桌子填充页面加载正确的时候,但真的没有,因为从时间数据的变化,以随时的帮助。

If I inline the json data inside the <script> block instead of making an ajax json REST service call, the table populates correctly when the page loads, but that really doesn't help since the data changes from time to time.

推荐答案

数据是异步获取,但你同步使用。然后第一个的getData 呼叫使用未解决的数据,这意味着没有数据的。

Your data are asynchronously fetched but you use it synchronously. Then first getData call uses unresolved data, which means no data at all.

键入的字符似乎记得的getData 用,这时候,解决了数据。这可以解释的数据显示在输入的第一个关键。

Typing a character seems to recall getData with, this time, resolved data. That would explain data showing on first key typed.

要等待数据被取出,实现这样的回调 ngTable 电话:

To wait for data being fetched, implement ngTable call in such a callback:

/* there, data are not fetched */
data.$promise.then(function (data) {
    /* there data are fetched, work with it */
});

这篇关于AngularJS ngTable延迟AJAX的数据显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆