When to get the width of an Angular directive?

人走茶凉 提交于 2019-12-11 09:19:47

问题


When and how can I get the length of a to-be-compiled div in Controller and/or Directive, the .length-wanted in this case, without resorting to $timeout? Or is there an event telling me that Angular's work is all done and I could go get its height/width?

<div ng-controller="testCtrl">
    <div get-length>
        <div class="length-wanted" ng-bind="arr"></div>
    </div>
</div>

Demo here: http://jsfiddle.net/luxiyalu/tm54k4je/


回答1:


Since it's possible that its size might change with resize, I eventually went with:

<div ng-controller="testCtrl">
    <div get-length>
        <div class="height-wanted" height="data.height" ng-bind="arr"></div>
    </div>
</div>

Directive:

app.directive('lengthWanted', function() {
  return {
    restrict: 'C',
    scope: {height: '='},
    link: function (scope, element) {
      scope.$watch(function() {
        return element.height();
      }, function(newVal) {
        scope.height = newVal;
      });
    }
  };
});

Of course, this is checking the height of the element with every $digest. You could optimise this by storing a resized property in scope and returning the watched function if it's set to false.



来源:https://stackoverflow.com/questions/26275200/when-to-get-the-width-of-an-angular-directive

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