Jean-Michel Provencher Jean-Michel Provencher - 1 year ago 56
CSS Question

Automatically resizing font-size in ng-repeat

I am currently trying to resize font-size to fit inside a fixed size div. I found this interesting piece of javascript code doing the job very well

$('#defect-text div').css('font-size', '1em');

while ($('#defect-text div').height() > $('#defect-text').height()) {
$('#defect-text div').css('font-size', (parseInt($('#defect-text div').css('font-size')) - 1) + "px");

For the following HTML code

<div ng-repeat="defect in surface.defects" class="new-page">
<div id="defect-text">
<div id="defect-title">{{ 'TYPE' | translate }}:</div>
{{ defect.type }}
<div id="defect-title">Emplacement du défaut:</div>
{{ defect.location }}
<div id="defect-title">Dimension du défaut:</div>
{{ defect.dimension }}
<div id="defect-title">Actions suggérées:</div>
{{ defect.future_operation }}
<div id="defect-title">Détail technique du défaut:</div>
{{ defect.description }}</div>

However, since the different div are inside an ng-repeat expression, my piece of javascript code will resize the font of every container with the desired size of the first one. Is there a way to change to code to select the current element of the ng-repeat and change only it's own css to fit the container?

thanks in advance

Answer Source

I think your problem is actually one of scope:

$('#defect-text div').css('font-size'...)

You're selecting ALL <div> descendants (no matter how deep) of the id="defect-text" element and modifying them at this time. Technically an ID MUST be unique (behavior is not well defined if you have multiple elements with the same ID), and I think your selector is grabbing ALL of the <div> contained within ANY #defect-text elements, which is probably a lot broader than you want, inside of this particular loop.

I would recommend modifying your ng-repeat block and replacing the ID using the angular expression language like

<div id="{{ }}">

then you can use $("#" + " div") to get all <div> descendants of a unique defect.

I'd also consider using the child selector "> div" instead of all descendants.