Javascript 范围值更新时运行角度指令
我编写了一个指令,将父元素的子元素设置为最高子元素的高度。以下是指令代码:Javascript 范围值更新时运行角度指令,javascript,angularjs,Javascript,Angularjs,我编写了一个指令,将父元素的子元素设置为最高子元素的高度。以下是指令代码: app.directive('equalHeightChildren', function(){ return function(scope, element, attrs){ var $tallest = element; $.each(element.children(), function(index, child){
app.directive('equalHeightChildren', function(){
return function(scope, element, attrs){
var $tallest = element;
$.each(element.children(), function(index, child){
if($(child).outerHeight() > $tallest.outerHeight()){
$tallest = $(child);
}
});
element.children().outerHeight($tallest.outerHeight() + 'px');
}
});
此代码在页面加载时运行,并正确调整高度。但是,我的应用程序中有一些范围变量可以更改这些子元素的高度,例如,选中复选框会在其中一个子元素中显示新表单,从而增加其高度。我希望当这些变量中的一个发生变化时,该指令能够重新运行,从而重新调整子元素的高度。然而,这似乎没有发生
当作用域变量发生变化时,是否有办法让指令运行?还是我的想法不正确?如果你想让它重新运行each,你可能需要一个观察者来观察正在变化的元素。 另一个选项是触发事件并让此指令处理它
app.directive('equalHeightChildren', function(){
return function(scope, element, attrs){
var setTallest = function(){
var $tallest = element;
$.each(element.children(), function(index, child){
if($(child).outerHeight() > $tallest.outerHeight()){
$tallest = $(child);
}
});
element.children().outerHeight($tallest.outerHeight() + 'px');
}
setTallest();
//Use one of these to cause the height to be reset
//$scope.$watch('myVar', function() {setTallest(); });
// $rootScope.on('eventTrigger', setTallest);
}
});
相关:。我想你需要某种类型的范围。$注意这里。我刚刚尝试了这个,由于某种原因,当我选中该框时,仍然没有看到侦听器函数启动。该框绑定到名为order.shippingAsBilling的值。因此,我的watch函数是:scope.$watchscope.order.shippingAsBilling,functionvalue{sethighest;};它在初始页面加载时工作,但当我选中该框以更改order.shippingAsBilling的值时,不会再次调用该函数。watch表达式需要是字符串。这似乎已经修复了它:scope.$watch'order.shippingAsBilling',functionvalue{sethighest;};