何时获取 Angular 指令的宽度? [英] When to get the width of an Angular directive?

查看:23
本文介绍了何时获取 Angular 指令的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我何时以及如何获得 Controller 和/或 Directive 中要编译的 div 的长度,.length-wanted 在这种情况下,不诉诸 $timeout?或者是否有事件告诉我 Angular 的工作已经完成,我可以去获取它的高度/宽度?​​

<div 获取长度><div class="length-wanted" ng-bind="arr"></div>

此处演示:http://jsfiddle.net/luxiyalu/tm54k4je/

解决方案

因为它的大小可能会随着调整大小而改变,所以我最终选择了:

<div 获取长度><div class="height-wanted" height="data.height" ng-bind="arr"></div>

指令:

app.directive('lengthWanted', function() {返回 {限制:'C',范围:{高度:'='},链接:功能(范围,元素){范围.$watch(function() {返回 element.height();},函数(新值){scope.height = newVal;});}};});

当然,这是用每个$digest检查元素的高度.您可以通过在 scope 中存储一个 resized 属性并在它设置为 false 时返回被监视的函数来优化它.

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/

解决方案

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.

这篇关于何时获取 Angular 指令的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆