2015-10-15 37 views
0

我想在我的指令中獲取父元素的高度。如何在我的場景中獲取父元素高度?

我有類似

(function(window, angular) { 
    var app = angular.module('myApp'); 
    app.directive('testElem', [ 
     function() { 
      return { 
       restrict: 'A', 
       template:'<a class="button"></a>', 
       link: function(scope, element) {       
        var height = angular.element(element).parent().height(); 
        console.log(height); 
        //the height is 0 because not all item.description are 
        //rendered 
       } 
      }; 
     } 
    ]); 
})(window, angular); 

HTML

<div id="container"> 
    <div ng-repeat="item in items"> 
     {{item.description}} 
    </div> 
    <a test-elem href="#"></a> 
</div> 

我想獲得的#container高度後,我有我的頁面呈現的所有{{item.description}}。只要doms完成後沒有item.description,我現在的代碼就會得到它的父母身高。

感謝您的幫助!

+0

所以指令在描述可用之前加載?你可能會首先「解析」你的描述,然後將它們注入你的控制器。 – SuperVeetz

回答

2

您應該能夠使用$timeout項目在頁面上呈現之後運行:

(function(window, angular) { 
    var app = angular.module('myApp'); 
    app.directive('testElem', [ 
     function($timeout) { 
      return { 
       restrict: 'A', 
       template:'<a class="button"></a>', 
       link: function(scope, element) { 
        $timeout(function() { 
         var height = angular.element(element).parent().height(); 
         console.log(height); //height should be accurate 
        }); 
       } 
      }; 
     } 
    ]); 
})(window, angular); 

$超時返回一個承諾,當延遲已通過其解決和超時功能提供被執行。 https://docs.angularjs.org/api/ng/service/$timeout

1

在你的指令中是用ng-repeat指令異步編譯的。你可以設定一個承諾並解決它。

angular.module('myApp', []) 
.controller('myController', ['$scope', '$q', '$timeout',function($scope, $q, $timeout) { 
    $scope.items = ['Item 1', 'Item 2', 'Item 3']; 

    var deferred = $q.defer(); 
    $scope.myPromise = deferred.promise; 

    $timeout(function() { 
     deferred.resolve() 
    }); 
}]) 
.directive('testElem', [ 
    function() { 
     return { 
      restrict: 'A', 
      template:'<a class="button"></a>', 
      link: function(scope, element) { 
       scope.myPromise.then(function(){ 
        var height = element.parent()[0].offsetHeight; 
        console.log(height); 
       });  
      } 
     }; 
    } 
]); 

這裏是工作示例: JsFiddle