我写了一个指令,允许你将一个 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/