问题
I would like to truncate text dynamically, on each data change and each window's resize event.
Lets's say I have a HTML:
<p ng-truncate='lines: 2'> Lorem ipsum dolor...</p>
My directive does the truncation, but still it lacks of re-truncation on window's resize.
angular.module('moduleName', [])
.directive 'ngTruncate', () ->
link: (scope, element, attributes) ->
// Direcive code here
$(window).on 'resize', ->
scope.$apply()
scope.$digest()
Unfortunatelly, $apply, nor $digest() do not work.
Moreover, I believe I should use $window somehow...
回答1:
Probably nothing has changed in $scope before you called $apply or $digest on resize.
Better add some function, eg.:
function onWindowChange() {
// do some changes to any
// attributes of scope
// and than apply them
scope.$digest()
}
// and call it on window resize
$window.resize(onWindowChange);
Or you may have function wich will change
any scope attr, wich you call on many
different events, and $scope.$watch this attr
and on change call $scope.$digest.
Maybe it would be easier to answer if you posted whole directive code here...
回答2:
Yes - you can use the $window property to keep a watch over the change to the size of the window.
Here is a fiddle.
Original discussion can be found here (from where the fiddle was picked)
来源:https://stackoverflow.com/questions/17057599/how-to-make-directive-re-render-view-in-angular