q.Then
q.Then

Reputation: 2753

Initializing Datatables with AngularJS

I have a controller that stores the rankings of songs based on sales. When the controller is initialized it already sends an HTTP GET request to get all the songs that will ever be needed to be displayed (for now the top 20 songs let's say, I think if I ever need to change this i.e. when the user is scrolling, load more songs, shouldn't be too difficult as I just need to change the scope array that holds everything, unless my thinking is incorrect). I absolutely love datatables and they offer easy pagination, sorting, etc. I really only need the sorting part of it. I have my HTML table here:

<div ng-controller="all_songs">
<table id="1" class="display">
    <thead>
        <tr>
            <th>Song Ranking</th>
            <th>Name</th>
            <th>Album</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="song in Songs">
            <td>{{song.song_ranking}}</td>
            <td>{{song.song_name}}</td>
            <td>{{song.parent_album}}</td>
        </tr>
    </tbody>
</table>
</div>

And this is my angularJS code:

indexMod.controller('all_songs', ['$scope', '$http', 'getSongsRankingURL', function($scope, $http, getSongsRankingURL) {
    var getPara = 'dev=true&getID=2';
    $http.get(getSongsRankingURL + getPara) //Fetch the song information for ruby voted songs that are currently airing
        .success(function(songs) {
            $scope.Songs = songs;
        })
        .error(function(exception) {
            alert(exception);
        });
}]);

My question is how do I initialize the table with AngularJS? Including what Datatables told me to do:

<script>
$(document).ready(function(){
  $('1').DataTable();
 });
 </script>

Has no effect on table, but I did include it inside the ng-app of my DOM. Is this because I am including this jQuery code inside a AngularJS bootstrapped DOM or am I doing this call wrong? I really have no idea how to use jQuery. Is there a better alternative way? I checked the console and there are no errors appearing and I already included all the files datatables told me to include. I included the jQuery CDN as well.

Upvotes: 1

Views: 4553

Answers (1)

m59
m59

Reputation: 43745

With Angular, you use directives to manipulate the DOM, and the elements are injected for your use as parameters. Selectors like $('1') are only working against you. This is how you would properly get the element reference to call the function.

<!-- add the directive to your element -->
<table my-directive> 
// create your directive
app.directive('myDirective', function() {
  return {
    // angular passes the element reference to you
    compile: function(element) {
      $(element).DataTable();
    }
  }
});

That probably isn't going to solve your problem, but fortunately for you, someone else has already ported this into an Angular directive: http://l-lin.github.io/angular-datatables/#/gettingStarted

Upvotes: 2

Related Questions