When to get the width of an Angular directive?

2019-07-31 22:42发布

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条回答
We Are One
2楼-- · 2019-07-31 23:38

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.

查看更多
登录 后发表回答