如何在Angular中制作指令重新渲染视图? [英] How to make directive re-render view in Angular?
问题描述
我想在每次数据更改和每个窗口的调整大小事件时动态截断文本.
I would like to truncate text dynamically, on each data change and each window's resize event.
假设我有一个 HTML:
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()
很遗憾,$apply
和 $digest()
都不起作用.
Unfortunatelly, $apply
, nor $digest()
do not work.
此外,我相信我应该以某种方式使用 $window
...
Moreover, I believe I should use $window
somehow...
推荐答案
在调用 $apply
或 $digest<之前,
$scope
中可能没有任何变化/code> 调整大小.
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);
或者你可能有会改变的功能任何范围 attr,您需要调用很多不同的事件,以及 $scope.$watch
这个属性并在更改调用 $scope.$digest
.
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...
这篇关于如何在Angular中制作指令重新渲染视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!