如何在数据已经通过AJAX在AngularJS装我重新初始化数据表? [英] How do I re-initialize datatables AFTER data has loaded via AJAX in AngularJS?

查看:302
本文介绍了如何在数据已经通过AJAX在AngularJS装我重新初始化数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularJS和数据表与服务器端脚本通过AJAX来获取数据。

我的控制器是这样的:

  VAR currentJobId = $ stateParams.jobId;
VAR selectedJobId = $ rootScope.currentJob;

如果(currentJobId!== selectedJobId){
    $ rootScope.currentJob = $ stateParams.jobId;
    VAR数据= {
        ID:$ stateParams.jobId
    }
    $ http.post('HTTP://localhost/angular/scripts/getJob.php,数据).success(功能(海图){
        $ scope.job = thedata.information;
        $ scope.jobNotes = thedata.notes;
        $ scope.jobMaterialUsage = thedata.materialUsage;
        $ scope.jobItems = thedata.jobItems;
        $ scope.jobSubcontractorCosts = thedata.subcontractorCosts;
        $ scope.jobBondMiscCosts = thedata.bondMiscCosts;
        $ scope.jobEmployeeTime = thedata.employeeTime;
    });
}
 

这是示例表如下:

 <表类=桌桌条纹表悬停行通ID =employeeTimeTableUI-JQ =dataTable的用户界面,选项=tableOptions>
    < THEAD>
        &其中; TR>
            <第i个员工姓名和LT; /第i个
            百分位个总时间和LT; /第i个
        < / TR>
    < / THEAD>
    < TBODY>
        < TR NG重复=时间jobEmployeeTimeNG点击=goToEmployee(job.id,time.id);>
            &其中; TD> {{time.name}}&所述; / TD>
            &其中; TD> {{time.total_minutes}}&所述; / TD>
        < / TR>
    < / TBODY>
    < TFOOT>
        &其中; TR>
            <第i个员工姓名和LT; /第i个
            百分位个总时间和LT; /第i个
        < / TR>
    < / TFOOT>
< /表>
 

所以它基本上是看是否作业ID发生了变化,如果它发生了变化,它使Ajax调用了新的工作方式 - 如果它没有改变它什么都不做。我的问题是,我的表正被使用的数据加载之前,初始化数据表时,我打刷新。从页面导航的路程,回到它正确初始化数据表,而是直接将网​​页通过URL或刷新时,它只是把数据在表格的上方,同时仍保持无表可用数据的,没有数据表功能的工作。

解决方案

通过的角UI路由器你可以和解决您的后端数据的状态控制器被调用之前做到这一点。

请看看下面或本的jsfiddle

演示

这是一个与输出数据表,但是这可能是比较容易的部分的补充。

(函数(){ 使用严格的; angular.module('demoApp',['ui.router','angularSpinner'])     .RUN(启动)     .factory('jobsDataService',JobsDataFactory)     的.config(配置); 功能JobsDataFactory($ HTTP){     VAR backendUrl =HTTP://jsonplaceholder.typi$c$c.com;          返回 {         得到:函数(ID){             返回$ http.jsonp(backendUrl +'/职位/+ ID +'?回调= JSON_CALLBACK')                 。然后(函数(响应){                     返回response.data;             });         }     }; } 功能配置($ urlRouterProvider,$ stateProvider){     $ urlRouterProvider.otherwise('/工作/ 1');          $ stateProvider         .state('工作',                {                    网址:'/职位/:身份证',                    templateUrl:谐音/ post.html',                    解决: {                        工作:功能(jobsDataService,$ stateParams){                            的console.log($ stateParams.id);                            返回jobsDataService.get($ stateParams.id);                        }                    },                    控制器:函数($范围,作业){                        执行console.log(工作);                        $ scope.job =工作;                    }                }); } 功能启动($ rootScope){     //仅用于装载微调     $ rootScope         。在('$ stateChangeStart'$,             功能(事件,toState,toParams,fromState,fromParams){                 $ rootScope.loading = TRUE;         });     $ rootScope         。在('$ stateChangeSuccess'$,             功能(事件,toState,toParams,fromState,fromParams){                 $ rootScope.loading = FALSE;         }); }      })();

&LT;脚本SRC =htt​​ps://cdnjs.cloudflare.com/ajax /libs/angular.js/1.4.3/angular.js"></script> &所述;脚本的src =htt​​ps://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.1/spin.min.js&GT;&所述; /脚本&GT; &LT;脚本src="https://cdnjs.cloudflare.com/ajax/libs/angular-spinner/0.6.2/angular-spinner.js"></script> &LT;脚本src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script> &LT; D​​IV NG-应用程序=demoApp&GT;     &LT;跨度我们微调=NG-IF =加载&GT;&LT; / SPAN&GT;     &LT; A HREF =#UI-SREF ='作业({ID:1})&GT;工作1&LT; / A&GT;     &LT; A HREF =#UI-SREF ='作业({ID:2})&GT;工作2'; / A&GT;     &所述; A HREF =#UI-SREF ='作业({编号:3})'&GT;作业3'; / a取代;     &LT;格UI视图=&GT;&LT; / DIV&GT;          &LT;脚本类型=文/ NG-模板ID =谐音/ post.html&GT;         &其中p为H.;调试编号= {{job.id}}&所述; / P&GT;         &LT; H1&GT; {{job.tit​​le}}&LT; / H1&GT;         &其中p为H.; {{job.body}}&所述; / P&GT;     &LT; / SCRIPT&GT; &LT; / DIV&GT;

I am using AngularJS and Datatables together with a server-side script to obtain data via AJAX.

My controller looks like:

var currentJobId = $stateParams.jobId;
var selectedJobId = $rootScope.currentJob;

if (currentJobId !== selectedJobId) {
    $rootScope.currentJob=$stateParams.jobId;
    var data = {
        id: $stateParams.jobId
    }
    $http.post('http://localhost/angular/scripts/getJob.php', data).success(function (thedata) {
        $scope.job = thedata.information;
        $scope.jobNotes = thedata.notes;
        $scope.jobMaterialUsage = thedata.materialUsage;
        $scope.jobItems = thedata.jobItems;
        $scope.jobSubcontractorCosts = thedata.subcontractorCosts;
        $scope.jobBondMiscCosts = thedata.bondMiscCosts;
        $scope.jobEmployeeTime = thedata.employeeTime;
    });
}

An example table looks like:

<table class="table table-striped table-hover row-links" id="employeeTimeTable" ui-jq="dataTable" ui-options="tableOptions">
    <thead>
        <tr>
            <th>Employee Name</th>
            <th>Total Hours</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="time in jobEmployeeTime" ng-click="goToEmployee(job.id,time.id);">
            <td>{{time.name}}</td>
            <td>{{time.total_minutes}}</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th>Employee Name</th>
            <th>Total Hours</th>
        </tr>
    </tfoot>
</table>

So it is basically seeing if the job id has changed and if it has changed, it makes the ajax call for the new job info - if it has not changed it does nothing. The problem I have is that my table is being initialized with datatables before the data loads when I hit refresh. Navigating away from the page and going back to it initializes datatables correctly, but when going DIRECTLY to the page through URL or refresh it just puts the data at the top of the table while still maintaining "No data available in table" and none of the datatables functions working.

解决方案

With Angular ui-router you could do it with resolving your backend data before the state controller gets called.

Please have a look at the demo below or in this jsFiddle.

It's with-out datatables but that's probably the easier part to add.

(function() {
'use strict';

angular.module('demoApp', ['ui.router', 'angularSpinner'])
    .run(StartUp)
    .factory('jobsDataService', JobsDataFactory)
    .config(Config);

function JobsDataFactory($http) {
    var backendUrl = 'http://jsonplaceholder.typicode.com';
    
    return {
        get: function(id) {
            return $http.jsonp(backendUrl + '/posts/'+id +'?callback=JSON_CALLBACK')
                .then(function(response) {
                    return response.data;
            });
        }
    };
}

function Config($urlRouterProvider, $stateProvider) {
    $urlRouterProvider.otherwise('/jobs/1');
    
    $stateProvider
        .state('jobs',
               {
                   url: '/jobs/:id',
                   templateUrl: 'partials/post.html',
                   resolve: {
                       job: function(jobsDataService, $stateParams) {
                           console.log($stateParams.id);
                           return jobsDataService.get($stateParams.id);
                       }
                   },
                   controller: function($scope, job) {
                       console.log(job);
                       $scope.job = job;
                   }
               });
}

function StartUp($rootScope){
    // only used for loading spinner
    $rootScope
        .$on('$stateChangeStart', 
            function(event, toState, toParams, fromState, fromParams){ 
                $rootScope.loading = true;
        });

    $rootScope
        .$on('$stateChangeSuccess',
            function(event, toState, toParams, fromState, fromParams){ 
                $rootScope.loading = false;
        });

}
    
})();

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.1/spin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-spinner/0.6.2/angular-spinner.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>

<div ng-app="demoApp">
    <span us-spinner="" ng-if="loading"></span>
    <a href="#" ui-sref='jobs({id: 1})'>job 1</a>
    <a href="#" ui-sref='jobs({id: 2})'>job 2</a>
    <a href="#" ui-sref='jobs({id: 3})'>job 3</a>
    <div ui-view=""></div>
    
    <script type="text/ng-template" id="partials/post.html">
        <p>debug id = {{job.id}}</p>
        <h1>{{job.title}}</h1>
        <p>{{job.body}}</p>
    </script>
</div>

这篇关于如何在数据已经通过AJAX在AngularJS装我重新初始化数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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