How to make directive re-render view in Angular?

那年仲夏 提交于 2019-12-07 23:46:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!