【发布时间】:2015-09-11 04:44:22
【问题描述】:
我想在 ng-repeat 完成 angular 后截断文本。
我发现一个简单的方法是使用 limitTo 过滤器来限制文本长度。 但是,我想按其实际宽度转动文本。
参考下面的页面,这是我的代码: 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');
});
};
}
}
});
问题是,当 $scope.$on('ngRepeatFinished') 运行时,数据并没有真正加载到 dom,$thisH4.children('span').width() 返回 0,
只有当我通过 setTimeout() 设置 0.4 秒延迟时它才有效,但我认为这样做没有意义。
有什么办法可以解决这个问题还是我最好坚持limitTo过滤?
谢谢
【问题讨论】:
标签: javascript jquery angularjs angularjs-ng-repeat truncate