簡體   English   中英

如果范圍值更新,則Angular指令運行

[英]Angular directive run if scope values update

我寫了一條指令,將父元素的子元素設置為等於最高子元素的高度。 這是指令代碼:

    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');
        }
    });

此代碼在頁面加載並正確調整高度時運行。 但是,我的應用程序中有某些范圍變量,可以更改這些子元素的高度(例如,選中復選框會在其中一個子元素中顯示新表單,從而增加其高度)。 我希望當這些變量之一更改時,該指令會重新運行,從而重新調整子元素的高度。 但是,這似乎沒有發生。

當范圍變量更改時,是否有一種方法可以運行指令? 還是我在想這個錯誤?

如果您希望它重新運行,則可能需要一個觀察者來監視正在更改的元素。 另一種選擇是觸發一個事件並讓此指令處理它。

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);
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM