lemoncodes
lemoncodes

Reputation: 2421

AngularJS DataTables Controller Markup

Recently i have been tweaking this module on angularJS angular-datatables ajax and now i am having this error

angular.min.js:117 TypeError: Cannot read property 'aDataSort' of undefined

I just found out that on the markup upong definition of controller in html element there is this "as" keyword after the controller name and it solved my error.

Now, the question is what is that "as" keyword in that definition and would it be possible not to use it? please refer to the code snippet below

Not working Code:

<div ng-controller="mainCtrl">
    <table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" class="table table-hover table-bordered table-striped"></table>
</div>

Working Code:

<div ng-controller="mainCtrl as showCase">
    <table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" class="table table-hover table-bordered table-striped"></table>
</div>

Also i tried this code but it didn't work

<div ng-controller="mainCtrl">
    <table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-hover table-bordered table-striped"></table>
</div>

This is my controller and app js

var app = angular.module('medrec', ['ngRoute','ngResource','ui.bootstrap','datatables'])
                 .constant('API_URL', window.location.href);

app.controller('mainCtrl',['$scope',
                           'API_URL',
                           'DTOptionsBuilder',
                           'DTColumnBuilder',
                           '$resource',
    function($scope, API_URL, DTOptionsBuilder, DTColumnBuilder, $resource){


        var vm = this;
        vm.dtOptions = DTOptionsBuilder.fromSource(API_URL+'tests/data.json')
            .withPaginationType('simple');
        vm.dtColumns = [
            DTColumnBuilder.newColumn('id').withTitle('ID'),
            DTColumnBuilder.newColumn('firstName').withTitle('First name'),
            DTColumnBuilder.newColumn('lastName').withTitle('Last name').notVisible()
        ];
}]);

Upvotes: 0

Views: 647

Answers (1)

Hadi
Hadi

Reputation: 17289

when using this instead of $sope in controller then you should use controller as syntax in veiw.

in controller:

  var vm = this;

in view

   ng-controller="ctrl as c"

and also for access scope function or variable using c.dtOptions as you see in your example.

Upvotes: 1

Related Questions