Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using AngularJS to populate my datatable. What I want to know is how can I populate the datatable based on the dropdownlist

This is my dropdownlist

<div>
     Get Users with Role:
     <select id="ddlRole" data-ng-model="selectedRole" data-ng-change="populateDataTable()" data-ng-options="v.name for (k,v) in roles"></select>
     <input type="hidden" value="{{selectedRole}}" />
 </div>

This is my angular code

$scope.roles = [
    {name: 'XXX' },
    {name: 'YYY' }
];
$scope.selectedRole = $scope.roles[0];

//onchange event
 $scope.populateDataTable = function () {
    $scope.selectedRole = $scope.selectedRole.name;
    RefreshDataTable(); //TODO
};

How can I change this to make an ajax call to retreive the data, populate the datatable based on the dropdownlist value and retain the value of dropdownlist as well.

I'm sure we can do this using JQuery but I dont want to mix these and make a mess. Is there any way I can acheive this using AngularJS?

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

Here is a simple data table directive:

    appModule.directive('dataTable', [function () {
    return function (scope, element, attrs) {

        // apply DataTable options, use defaults if none specified by user
        var options = {};
        if (attrs.myTable.length > 0) {
            options = scope.$eval(attrs.myTable);
        } else {
            options = {
                "bStateSave": true,
                "iCookieDuration": 2419200, /* 1 month */
                "bJQueryUI": true,
                "bPaginate": false,
                "bLengthChange": false,
                "bFilter": false,
                "bInfo": false,
                "bDestroy": true
            };
        }

        // Tell the dataTables plugin what columns to use
        // We can either derive them from the dom, or use setup from the controller           
        var explicitColumns = [];
        element.find('th').each(function (index, elem) {
            explicitColumns.push($(elem).text());
        });
        if (explicitColumns.length > 0) {
            options["aoColumns"] = explicitColumns;
        } else if (attrs.aoColumns) {
            options["aoColumns"] = scope.$eval(attrs.aoColumns);
        }

        // aoColumnDefs is dataTables way of providing fine control over column config
        if (attrs.aoColumnDefs) {
            options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
        }

        if (attrs.fnRowCallback) {
            options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
        }

        // apply the plugin
        var dataTable = element.dataTable(options);



        // watch for any changes to our data, rebuild the DataTable
        scope.$watch(attrs.aaData, function (value) {
            var val = value || null;
            if (val) {
                dataTable.fnClearTable();
                dataTable.fnAddData(scope.$eval(attrs.aaData));
            }
        });

        if (attrs.useParentScope) {
            scope.$parent.dataTable = dataTable;
        } else {
            scope.dataTable = dataTable;
        }
    };
}]);

Then initialize it in your controller. Override fnServerData method, append your selected value (selected role) and filter data on server side.

    $scope.overrideOptions = {
            "bStateSave": true,
            "iDisplayLength": 8,
            "bProcessing": false,
            "bServerSide": true,
            "sAjaxSource": 'Data/Get',
            "bFilter": false,
            "bInfo": true,
            "bLengthChange": false,
            "sServerMethod": 'POST',        ,
            "fnServerData": function(sUrl, aoData, fnCallback, oSettings) {
                var data = {
                    dataTableRequest: aoData,
                    selectedDropDownValue: $scope.selectedRole
                };

                $http.post(sUrl, data).success(function (json) {
                    if (json.sError) {
                        oSettings.oApi._fnLog(oSettings, 0, json.sError);
                    }

                    $(oSettings.oInstance).trigger('xhr', [oSettings, json]);
                    fnCallback(json);
                });
            }
     };

var columnDefs = [
                        {
                            "mData": "id",                            
                            "bSortable": false,
                            "bSearchable": false,                            
                            "aTargets": ['tb-id']
                        },
                        {
                            "mData": "data",
                            "aTargets": ['tb-data']                            
                        }
];

Refresh the datatable on select change.

$scope.populateDataTable = function () {         
     if ($scope.dataTable) {
         $scope.dataTable.fnDraw();
     }  
  };

Html markup:

<table  class="display m-t10px" data-table="overrideOptions" ao-column-defs="columnDefs">
      <thead>
          <tr>
              <th class="tb-id"></th>           
              <th class="tb-data></th>               
          </tr>
      </thead>
      <tbody>
      </tbody>
</table>
share|improve this answer
    
May I know which part of it triggers an onchangeevent on dropdownlist? Thank You. –  user Jan 30 at 9:12
    
@Sup A added a missing part. –  MajoB Jan 30 at 9:20
    
Is dataTable the id of the table? Because it isn't refreshing the table. Am I missing something? –  user Jan 30 at 9:27
    
@Sup the $scope.dataTable is a variable which contains a reference to the dataTable plugin's instance. The variable is initialized inside the directive. –  MajoB Jan 30 at 9:35
    
I was missing dataTable plugin's instance then. Thank You. –  user Jan 30 at 9:59
show 2 more comments

Hope above your code is in controller. Inject $http and make a $http get or post call

$scope.populateDataTable = function () {
     $scope.selectedRole = $scope.selectedRole.name;
      $http.get('api/controller', function(result){
        //response from the service call in result
       });
  };
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.