dynamically disable angularjs datable columns using for loop

I am working with Angularjs data table where all my columns are generated dynamically except first and last two columns. I need to disable sorting for these dynamic columns so I am running a for loop for those columns. My for loop starts from 1 and run up to 4. The problem is though the for loop run from 1 to 3 but I am getting only the value 3 from the for loop which is the last value of the loop. As a result instead disabling column 2,3,4 it is just disabling column number 4.so how to set column disable options for 2,3 and 4th column using for loop?

My code:

$scope.ln=4;
for(var i=1;i<$scope.ln;i++){
   $scope.vm.dtColumnDefs = [
   DTColumnDefBuilder.newColumnDef(i).notSortable()
];

}

var app = angular.module('myApp',['datatables']);
app.controller('MyCtrl', function($scope,DTOptionsBuilder,DTColumnBuilder,DTColumnDefBuilder) {

    $scope.list = [
        {"eid":"10","dyn1":"dval1","dyn2":"dval2","dyn3":"dval3","sales":"20"},
       
        {"eid":"30","dyn1":"dval1","dyn2":"dval2","dyn3":"dval3","sales":"20"},
        {"eid":"40","dyn1":"dval1","dyn2":"dval2","dyn3":"dval3","sales":"20"}
    ];
    $scope.vm = {};

$scope.vm.dtOptions = DTOptionsBuilder.newOptions()
      .withOption('order', [0, 'asc']);

$scope.ln=4;
for(var i=1;i<$scope.ln;i++){
   $scope.vm.dtColumnDefs = [
   DTColumnDefBuilder.newColumnDef(i).notSortable()
];

}
});
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="http://phpflow.com/demo/angular_datatable_demo/angular-datatables.min.js"></script>
  <script src="http://phpflow.com/demo/angular_datatable_demo/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
  <link rel="stylesheet" href="http://phpflow.com/demo/angular_datatable_demo/datatables.bootstrap.css"> 
</head>
<div class="container">
<div ng-app="myApp" ng-controller="MyCtrl">
<table  class="table table-striped table-bordered" dt-options="vm.dtOptions" dt-column-defs="vm.dtColumnDefs" datatable="ng">
    <thead>
      <tr>
     <th>Employee ID</th>
    <th>dynamic clm1</th>
    <th>dynamic clm2</th>
    <th>dynamic clm3</th>
  <th>sales</th>

</thead>
    <tbody>
  
   <tr ng-repeat="data in list">
      <td> {{ data.eid }} </td>
      <td> {{ data.dyn1 }} </td>
      <td> {{ data.dyn2 }} </td>
      <td> {{ data.dyn3 }} </td>
      
      <td> {{ data.sales }} </td>
      </tr>
</tbody>
</table>
</div>

Answer

At last i have solved it myself using array push

$scope.vm.dtColumnDefs = [  ];
for (var i=0; i<$scope.ln; i++) {

$scope.vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i).notSortable()); 

}

Leave a Reply

Your email address will not be published. Required fields are marked *