javascript - 用于观察高度变化的 AngularJS 指令

标签 javascript html css angularjs angularjs-directive

我写了一个指令,允许你将一个 CSS 属性绑定(bind)到另一个的高度

m.directive('bindToHeight', function ($window) {

    return {
        restrict: 'A',

        link: function (scope, elem, attrs) {
            var attributes = scope.$eval(attrs['bindToHeight']);
            var targetElem = angular.element(document.querySelector(attributes[1]));

            // Watch for changes
            scope.$watch(
                function () {
                    return targetElem.height();
                },
                function (newValue, oldValue) {
                    if (newValue != oldValue) {
                        elem.css(attributes[0], newValue);
                    }
                });
        }
    };
});

用法:

<div bind-to-height="['bottom','#theContainer']">

现在我注意到它只有在 #theContainer 的内容被更新两次后才有效。第一次似乎发送高度为 0,第二次它正确获取高度。

这个 div 是从另一个 Angular Controller 更新的,高度可以根据其中的内容而改变。我写这篇文章的原因是因为有东西堆叠(绝对位置)在它上面,需要调整它的高度来匹配。

当我第一次运行该页面时,我得到以下值

  • 旧值:287,新值:287
  • 旧值:287,新值:0

是我写错了指令还是有更好的方法来做到这一点?

最佳答案

尝试深入观察您的元素:

m.directive('bindToHeight', function ($window) {

    return {
        restrict: 'A',

        link: function (scope, elem, attrs) {
            var attributes = scope.$eval(attrs['bindToHeight']);
            var targetElem = angular.element(document.querySelector(attributes[1]));

            // Watch for changes
            scope.$watch(
                function () {
                    return targetElem.height();
                },
                function (newValue, oldValue) {
                    if (newValue != oldValue) {
                        elem.css(attributes[0], newValue);
                    }
                }, true);//ADD A BOOLEAN TO DEEPWATCH ALL THE PROPERTIES OF THE OBJECT
        }
    };
});

关于javascript - 用于观察高度变化的 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29127261/

相关文章:

javascript - 检查浏览器宽度并执行一个 Javascript 文件并覆盖另一个 Javascript

javascript - 在javascript中将字符串数组转换为数字数组

javascript - Typed.js - 如何多次调用函数 onClick

html - 在 CSS 中为标题(h1、h2 ...)定义全局设置后,是否可以添加特定于标题的设置?

javascript - Instafeed 脚本不工作

php - 获取输入类型单选的值并根据选择的类型重定向

javascript - jQuery 点击重复两次

javascript - IE8 中 Javascript 错误最可能的原因是什么?

javascript - HTML DOM 基本抓取

html - 单击搜索框时围绕搜索框的边框