Friday, 25 January 2019

DataTables not found in Angular Datatables using Webpack Encore

I've been upgrading a Symfony application from 3.4 to 4.2.2, everything is fine but I cannot get DataTables to function via yarn install and webpack encore with angular-datatables.

How I've set it up

Yarn install:

yarn add jquery@2.1.4
yarn add angular@1.4.8
yarn add datatables.net@1.10.19
yarn add datatables.net-dt@1.10.11
yarn add angular-datatables@0.6.2

Added those files to my Webpack app.js along with jQuery:

var $ = require('jquery');
require('datatables.net');
require('datatables.net-dt');
require('angular');
require('angular-datatables');

Included the app.js inside of my Webpack config file:

var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')

    .addEntry('app', './assets/js/app.js')

    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())
    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

and included the above in my front-end template via:



The Error

The above results in the following Javascript error which seems to show the DataTables API is not accessible.

Uncaught TypeError: Cannot read property 'Api' of undefined
at initAngularDataTables (angular-datatables.js:478)
at Object.invoke (angular.js:4523)


/* @ngInject */
function initAngularDataTables() {
    if ($.fn.DataTable.Api) {
        /**
         * Register an API to destroy a DataTable without detaching the tbody so that we can add new data
         * when rendering with the "Angular way".
         */
        $.fn.DataTable.Api.register('ngDestroy()', function(remove) {
            remove = remove || false;




Possible Solution

I've tried the following hacky fix but it means I have to have my Angular code in the same app.js file else it doesn't work. It also means some functions still fail...

global.$ = global.jQuery = require('jquery');

require('jquery-ui');
require('bootstrap');
require('admin-lte');
require('datatables.net-dt');
global.moment = require('moment');

$.fn.dataTable = $.fn.DataTable = global.DataTable = require('datatables.net');

Error:

TypeError: _oTable.ngDestroy is not a function
    at _destroyAndCompile (angular-datatables.js:947)



from DataTables not found in Angular Datatables using Webpack Encore

No comments:

Post a Comment