使用自定义指令当ng-repeat加载完数据后执行js方法。
实战案例:
问题:使用datatables+angular生成表格时,往往是循环去生成表体内容,而我们也需要当数据完全加载生成出来后再执行datatables的渲染方法,如何实现呢?
自定义了一条指令:
//on-finish-render="ngRepeatFinished" load js after render datas
UserManagerApp.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
解释下:
link中当scope中的$last(也就是最后一条数据),加载完毕后触发’ngRepeatFinished’。
scope.$emit(‘ngRepeatFinished’);这句话就相当于trigger,会触发定义的事件监听:
也就是我们在controller中会添加:
$scope.$on('ngRepeatFinished', function( ngRepeatFinishedEvent ) {})
注:记得在html中需要加载数据的位置增加指令属性哦!
<tr ng-repeat="item in userList" on-finish-render>