When do we know the actual width of an element in Angular?

前端 未结 4 1309
梦如初夏
梦如初夏 2021-01-31 17:22

I\'m tring to create a directive that will center a div.

So far, I have this code:

app.directive(\"setcenter\", function () {
    return {
        scope:         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 18:16

    I had a similar issue and found that the dimensions were reliably correct when all the ng-ifs (or anything else using ngAnimate) on the page had been resolved - it's possible something similar is happening here. If so, this would do the trick without adding any new listeners:

    $scope.tryGetElementDimensions = function () {
        if (!angular.element("your-element") || ((angular.element("your-element")[0].classList).contains("ng-animate")
           $timeout(function() {
               $scope.tryGetElementDimensions()
           })
        }
        else {
            $scope.getElementDimensions()
        } 
    
    $scope.getElementDimensions = function (){
        //whatever you actually wanted to do
    }
    
    link: function (scope, element, attrs) {
        $scope.tryGetElementDimensions()
    }
    

    Angular adds ng-animate and ng-enter, ng-leave classes while it's animating and you can be confident it's finished when these classes have all been removed. $timeout without a second argument just waits for the next digest.

提交回复
热议问题