2015-01-12 3 views
4

Я пытаюсь получить высоту элементов в простом приложении AngularJS. См. Ниже. Что я делаю не так? Высота должна отличаться по сравнению с переносом строк, но я получаю 20 сообщений обо мне, независимо от того, что я ввел в массив меток.Высота элемента в пределах директивы AngularJS

Следующий код может быть выполнен здесь, в противном случае см. Ниже. http://js.do/code/49177

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <base href="/"> 

    <title>height of element in angularjs</title> 

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> 

    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular-route.js"></script> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 

    <script type="text/javascript"> 
    'use strict'; 

    var app = angular.module('heightApp', ['ngRoute', 'routing']); 

    app.controller('heightCtrl', ['$scope', function ($scope) { 
     $scope.labels = [ 
     'Hi there, I\'m a div.', 
     'Me too, I\'m also a div.', 
     'Can you see me, because I certainly can\'t see myself. I don\'t even know my own height. Isn\'t that just crazy?' 
     ]; 

    }]);  

    angular.module('routing', []).config(['$routeProvider', function($routeProvider) { 
     $routeProvider 
     .when('/', { 
      templateUrl: 'height.html', 
      controller: 'heightCtrl' 
     }); 
    }]); 

    angular.module('heightApp').directive('reportMyHeight', function() { 
     return function (scope, el, attrs) { 
      alert('offsetHeight = ' + el[0].offsetHeight); 
     } 
    }) 
    </script> 

</head> 

<body ng-app="heightApp"> 

<div class="container"> 
    <div ng-view></div> 
</div> 

</body> 

<script type="text/ng-template" id="height.html"> 
    <div class="row"> 
    <div class="col-sm-4" report-my-height ng-repeat="lbl in labels"> 
     {{ ::lbl }} 
    </div> 
    </div> 
</script> 

</html> 

ответ

8

Вы должны ждать до следующего цикла переваривать. Когда вы это сделаете сразу же в директиве, интерполяции {{ ::lbl }} внутри ng-repeat еще не расширились. Вы можете поместить его в $timeout, отключив аргумент applyDigest.

т.е., например:

angular.module('heightApp').directive('reportMyHeight', function($timeout) { 
    return function (scope, el, attrs) { 

     $timeout(init, false); 

     //Initialization 
     function init(){ 
     console.log('offsetHeight = ' + el[0].offsetHeight, el.html()); 
     } 

    } 
}); 

Plnkr

+0

$ timeout было сцепление! Я не мог понять, почему высота была настолько иной, что я смотрел. – dball

1

Другой способ убедиться, что вы получите высоту элемента использовать часы.

angular.module('heightApp').directive('reportMyHeight', function($timeout) { 
    return function (scope, el, attrs) { 
    scope.$watch('lbl', function(newval, oldval){ 
     alert(newval + '\n\n' + 'offsetHeight = ' + el[0].offsetHeight); 
    }); 
    } 
}) 

Он будет вызван только один раз, так как вы используете ::.

Смежные вопросы