0

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?

0

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

6 Comments

May I know which part of it triggers an onchangeevent on dropdownlist? Thank You.
@Sup A added a missing part.
Is dataTable the id of the table? Because it isn't refreshing the table. Am I missing something?
@Sup the $scope.dataTable is a variable which contains a reference to the dataTable plugin's instance. The variable is initialized inside the directive.
I was missing dataTable plugin's instance then. Thank You.
|
0

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
       });
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.