2015-07-01 35 views
0

我很新的角度,所以任何幫助將不勝感激。 我試圖根據屏幕大小(減去頁眉和頁腳)在頁面加載,窗口大小調整和另一個自定義事件(當用戶單擊以消耗內容時)垂直對齊div。所以我爲它寫了一個指令,我不確定這是否是正確的方法。我需要獲取指令中的元素高度才能使其工作。Angular JS - 在查看渲染前獲取指令中的元素高度

只是CSS,沒有任何JS,在我的情況下無法正常工作,該標記是嵌套/複雜的。我嘗試了不同的方法(inline-block的/翻譯/等)

問題:

  1. 當試圖首先進入指令時,元素高度爲0(零),我猜這是因爲視圖還沒有渲染。如果是這樣的話,這當然是有道理的,但我該如何解決它,所以當視圖轉換開始時,我已經通過JS做了所有必要的CSS更改?

  2. 如何在我加載更多內容或任何其他DOM操作之後「調用」該指令?

到目前爲止我的代碼:

app.directive('valign', ['$window', function ($window) { 
    return { 
     link: function ($scope, $element) { 
      var window = angular.element($window); 
      $scope.setHeight = function() { 
       var contentHeight = window.height() - $('#header').outerHeight(true) - $('#footer').outerHeight(true); 
       // Here I want to get the $element height so I can set the proper margin for it, for example 
      }; 
      $scope.setHeight(); 
      window.bind('resize', function() { 
       $scope.setHeight(); 
       $scope.$apply(); 
      }); 
     } 
    }; 
}]); 
+0

你沒有在你的鏈接功能 – gr3g

回答

0

您可以利用$超時這樣的:

app.directive('valign', ['$window', '$timeout', function ($window, $timeout) { 
    return { 
     link: function ($scope, $element) { 
      var window = angular.element($window); 
      $scope.setHeight = function() { 
       var contentHeight = window.height() - $('#header').outerHeight(true) - $('#footer').outerHeight(true); 
       // Here I want to get the $element height so I can set the proper margin for it, for example 
      }; 
      $timeout($scope.setHeight, 500, true); 
      window.bind('resize', function() { 
       $scope.setHeight(); 
       $scope.$apply(); 
      }); 
     } 
    }; 
}]); 

基本上,我們正在做的是後觸發自動調用setHeight功能我們希望該指令能夠呈現500毫秒的延遲。我們可以根據個人需求增加/減少時間。

+0

嗨了'$'跡象,這不起作用 - $超時($ scope.setHeight,0);超時解決方案只有在800毫秒後才起作用,但是太晚了,並且比邊緣css在內容中創建了一個「跳轉」,因爲它在轉換開始之後: – arielmorry

+0

我建議您在完成初始化/設置$ timeout。如果它已經完成然後重新運行這個東西當然,我不知道你到底在做什麼,所以幫不了你很多:( –

0

在$ timeout調用中調用$ scope.setHeight()。

從本質上說,沒有延遲的$超時會在DOM加載完成後發生,因此這些值將準備好使用。

+0

嗨,這不起作用 - $ timeout ($範圍。setHeight,0);超時解決方案只有在800毫秒後才起作用,但比起邊緣css在內容中創建一個「跳轉」,因爲它在轉換開始後: – arielmorry

0

解決!

我用安迪·劉易斯& Sidharth Panwar建議和錯亂$超時我的我的函數調用0毫秒,從而確保了該功能後,運行DOM準備好+我改變了標記,因此VALIGN指令將內部和NG-視圖(在我的情況下,ui-view),使視圖進入轉換之前應用更改。

最後的代碼是:

app.directive('valign', ['$window', '$timeout', function ($window, $timeout) { 
    return { 
     link: function ($scope, $element) { 
      var window = angular.element($window); 
      $scope.setHeight = function() { 
       var contentHeight = window.height() - $('#header').outerHeight(true) - $('#footer').outerHeight(true); 
       $element.css('margin-top',(contentHeight - $element.outerHeight(true)) /2); 
      }; 
      $timeout($scope.setHeight, 0); 
      window.bind('resize', function() { 
       $scope.setHeight(); 
       $scope.$apply(); 
      }); 
     } 
    }; 
}]); 

和標記:

<div ui-view> 
    <div valign></div> 
</div>