使用 AngularJS 初始化数据表

Initializing Datatables with AngularJS

我有一个控制器,可以根据销量存储歌曲的排名。当控制器初始化时,它已经发送了一个 HTTP GET 请求来获取所有需要显示的歌曲(现在是前 20 首歌曲,我想如果我需要改变它,即当用户滚动时,加载更多歌曲,应该不会太难,因为我只需要更改包含所有内容的范围数组,除非我的想法不正确)。我非常喜欢 datatables,它们提供了简单的分页、排序等功能。我真的只需要它的排序部分。我的 HTML table 在这里:

<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>

这是我的 angularJS 代码:

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

我的问题是如何用 AngularJS 初始化 table?包括 Datatables 让我做的事情:

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

对 table 没有影响,但我确实将其包含在 DOM 的 ng-app 中。这是因为我将此 jQuery 代码包含在 AngularJS 自举 DOM 中,还是我做错了这个调用?我真的不知道如何使用jQuery。有更好的替代方法吗?我检查了控制台,没有出现任何错误,而且我已经包含了 datatables 告诉我要包含的所有文件。我也包含了 jQuery CDN。

使用 Angular,您可以使用指令来操作 DOM,然后注入元素以供您用作参数。 $('1') 这样的选择器只会对你不利。这就是您正确获取元素引用以调用函数的方式。

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

这可能无法解决您的问题,但对您来说幸运的是,其他人已经将其移植到 Angular 指令中:http://l-lin.github.io/angular-datatables/#/gettingStarted