Skip to content
This repository was archived by the owner on Feb 2, 2025. It is now read-only.

When live switching the language with angular-translate, angular-datatables does not change/recognise the current language #351

Closed
Chalkin opened this issue Jun 22, 2015 · 8 comments
Milestone

Comments

@Chalkin
Copy link

Chalkin commented Jun 22, 2015

I use angular-translate with angular-datatables and implemented a language switch between german and english (Explained here: http://angular-translate.github.io/docs/#/guide/07_multi-language ) Switching language works well but not with angular-datatables. When i switch angular-datatables keeps the old translations for the table header.

*angular-datatables Controller:

It's loading the datatables data via json with a promise and then draws the table. It also refreshes the table every 5 minutes. I implemented a public function "rerenderTable" which i call when switching the app language.

controller('DashboardCtrl', ['$scope', '$rootScope', 'DTOptionsBuilder', 'DTColumnBuilder', 'DTInstances', '$resource',
    '$interval', '$translate',
    function($scope, $rootScope, DTOptionsBuilder, DTColumnBuilder, DTInstances, $resource, $interval, $translate)
{
    $scope.initTargetPackaging = function initTargetPackaging()
    {
        $scope.sourceUrl = 'json/v1.0.0/dashboard/datatables/myjson1.json';
    };

    $scope.initTargetConversion = function initTargetConversion()
    {
        $scope.sourceUrl = 'json/v1.0.0/dashboard/datatables/myjson2.json';
    };

    // Get the TargetPackaging JSON Data with promise AJAX call
    var vm = this;
    vm.dtOptions = DTOptionsBuilder.fromFnPromise( function()
    {
        return $resource($scope.sourceUrl).query().$promise;
    })
        .withOption('bInfo', false)
        .withOption('paging', false)
        .withOption('filter', false)
        .withOption('rowCallback', rowCallback);

    // Create the table columns
    vm.dtColumns = [
        DTColumnBuilder.newColumn('customer')
            .withTitle($translate('DIRECTIVES.DASHBOARD.DATATALBE_TARGET_PACKAGING_COLUMN_CUSTOMER')),
        DTColumnBuilder.newColumn('today')
            .withTitle($translate('DIRECTIVES.DASHBOARD.DATATALBE_TARGET_PACKAGING_COLUMN_TODAY')),
        DTColumnBuilder.newColumn('week')
            .withTitle($translate('DIRECTIVES.DASHBOARD.DATATALBE_TARGET_PACKAGING_COLUMN_7DAYS')),
        DTColumnBuilder.newColumn('month')
            .withTitle($translate('DIRECTIVES.DASHBOARD.DATATALBE_TARGET_PACKAGING_COLUMN_30DAYS'))
    ];

    vm.newPromise = newPromise;
    vm.reloadData = reloadData;
    vm.dtInstance = {};

    function newPromise()
    {
        return $resource($scope.sourceUrl).query().$promise;
    }

    /**
     * Reload the data
     */
    function reloadData()
    {
        var resetPaging = false;
        vm.dtInstance.reloadData(resetPaging);
    }

    // Trigger reloading - 5 mins
    $interval(reloadData, 300000);

    function rowCallback(nRow, aData)
    {
        // Add status CSS class if state is true
        if (aData['state'] != undefined
            && aData['state'] === true)
        {
            $(nRow).addClass('ad-status-inactive');
        }
    }

    $rootScope.rerenderTable = function()
    {
        vm.dtInstance.rerender();
    };
}]);

Function to switch language:

$scope.changeLang = function(key)
{
    $translate.use(key).then( function(key)
    {
        console.log("Sprache zu " + key + " gewechselt.");
        $rootScope.rerenderTable();
    },
    function(key)
    {
        // Trigger log error message (failure of switching language)
    });
};

Triggered here in html:

<div id="language-switch" class="col-xs-2" ng-controller="LanguageCtrl">
    <div class="inner">
        {{ 'MAIN_NAVIGATION.CHOOSE_LANGUAGE' | translate }}
        <span ng-click="changeLang('en')" class="lang-sm" lang="en"></span>
        <span ng-click="changeLang('de')" class="lang-sm" lang="de"></span>
    </div>
</div>

Summary: Switching languages works well. But not in the case of angular-datatables. It does not switch the language. But translating the strings is fine.

How do i get angular-datatables to rerender the table by using the currently chosen language?

@l-lin
Copy link
Owner

l-lin commented Jun 23, 2015

Interesting. I'll look into it when I'll find some time.

@Chalkin
Copy link
Author

Chalkin commented Jul 8, 2015

Any Ideas?

@l-lin
Copy link
Owner

l-lin commented Jul 21, 2015

Sorry. Had some RL stuffs to deal with.
Will check this as soon as I can.

@OlympicLarry
Copy link

Same problem here. My solution was to include the header definitions in the view and then not use the DTColumnBuilder because it always overwrites the column title.

<table id="assignments" datatable dt-options="vm.dtOptions" dt-columns="vm.dtColumns" dt-instance="vm.dtInstance" class="table table-hover" style="width:100%">
        <thead>
            <tr>
                <th>{{"manageExternalQualifications.name" | translate}}</th>
                <th>{{"manageExternalQualifications.email" | translate}}</th>
                <th>{{"manageExternalQualifications.itemName" | translate}}</th>
                <th>{{"manageExternalQualifications.itemCode" | translate}}</th>
                <th>{{"manageExternalQualifications.status" | translate}}</th>
            </tr>
        </thead>
    </table>

In my controller I build the dtColumn manually:

vm.dtColumns = [
        { 'mData': 'name' },
        { 'mData': 'email' },
        { 'mData': 'itemName' },
        { 'mData': 'itemCode' },
        { 'mData': 'status' }
]

@OlympicLarry
Copy link

I do have a related question though... how do I translate the data of a column. For example: "Status"
I thought this would work:

vm.dtColumns = [
        { 'mData': 'name' },
        { 'mData': 'email' },
        { 'mData': 'itemName' },
        { 'mData': 'itemCode' },
        {
            'mData': 'status',
            'mRender': function (data, type, full, meta) {
                return '<span translate="common.assignmentStatus.' + data.toLowerCase() + '"></span>';
            }
        },
    ];

but the translation never happens.

------- SOLVED ------

return $translate.instant("common.assignmentStatus." + data); // this works

@l-lin l-lin added the TODO label Jul 23, 2015
@l-lin l-lin added this to the v0.5.0 milestone Aug 17, 2015
l-lin added a commit that referenced this issue Aug 17, 2015
It's not possible if the title is provided in the options and not
directly in the HTML code.

Remove the assignation of the title in the factory if the title is
undefined.
@l-lin l-lin closed this as completed Aug 17, 2015
@l-lin
Copy link
Owner

l-lin commented Aug 17, 2015

As @OlympicLarry said, the workaround is to define the title directly in the HTML code.
For now, I don't think there will be a real solution if the titles must be defined in the datatable options as I don't want to adapt the module for angular-translate.

@haiboli
Copy link

haiboli commented Jun 28, 2016

分享下我的解决方式
first:
vm.dtColumns = [
DTColumnBuilder.newColumn('customer')
.withTitle('{{“DIRECTIVES.DASHBOARD.DATATALBE_TARGET_PACKAGING_COLUMN_CUSTOMER"|translate}}')),
];
second:

.withOption('headerCallback', headerCallback)

var headerCallback = function( thead, data, start, end, display ) {
$compile(angular.element(thead).contents())($scope);
}

@CamiloMartinez123
Copy link

CamiloMartinez123 commented Jan 21, 2022

1- Listen to the language change to render the table afterwards.

  $rootScope.$on('$translateChangeEnd', function (event, lang) {
    $scope.dtInstanceDocsSign.rerender();
  });

2-Inside constructor function of your table

     var headerCallback = function( thead, data, start, end, display ) {
            $compile(angular.element(thead).contents())($scope);
     }

3-

     $scope.dtOptions(your name) = DTOptionsBuilder
      .newOptions()
      .withOption('headerCallback', headerCallback)
      ..........your code

   $scope.dtColumns = [
     DTColumnBuilder.newColumn('code').withTitle(`${'<span translate>'}${'TAG'}${'</span>'}`).renderWith(your_code).withClass('center-text'),
    .........

Works for me ;)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants