我编写了一个指令,允许您将CSS属性绑定到另一个的高度
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是从另一个角度控制器更新的,高度可以根据其中的内容而变化。我写这篇文章的原因是因为它上面堆叠了一些东西(绝对位置),需要调整它的高度以匹配。
当我第一次运行页面时,我得到以下值
- 旧值: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
}
};
});