I want to truncate text after ng-repeat finished in angular.
I found a simple way is to use limitTo filter to limit text length. However, I want to turn text by it's actual width.
with reference of the page below, here is my code: Calling a function when ng-repeat has finished
html:
<div id="feedList">
<div ng-repeat="feed in feeds | orderBy: '-date' " feed-list-repeat-directive>
<h4><span>{{ feed.title }}</span></h4>
<!-- some more contents here -->
</div>
</div>
Javascript:
var app = angular.module('anApp', []);
app.controller('anCtrl', function($scope, $http) {
$http.get("data.php")
.success(function(response) {
$scope.feeds = response.feeds;
});
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
// truncate text by width #####################################
for(a=0; a<$('#feedList > div').length; a++){
$thisH4 = $('#feedList > div').eq(a).children('h4');
if($thisH4.width()<$thisH4.children('span').width()){
var txt = $thisH4.children('span').text();
while($thisH4.width()<$thisH4.children('span').width()){
txt = txt.substr(0,txt.length-1);
$thisH4.children('span').text(txt+'...');
}
};
};
//#######################################################
});
})
.directive('feedListRepeatDirective', function($timeout){
return {
restrict: 'A',
link: function(scope, element, attrs) {
if (scope.$last){
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
};
}
}
});
The problem is, when $scope.$on('ngRepeatFinished') runs, the data is not actually loaded to the dom, $thisH4.children('span').width() is returning 0,
It works only if I set a 0.4 sec delay by setTimeout(), but I think it is not sense making.
Is there any way to solve the problem or I better stick to limitTo filter?
thanks