Question

I'd like to compute the element scroller width, as the number of children x the width of first child. To do that, I have designed a directive hscroller.

The HTML is as follows:

<div class="scrollerContainer">
    <div id="photos" class="scroller" hscroller="hi!">
        <div ng-repeat="photo in stage.photos" 
            class="imageViewerBackground" 
            style="background-image: url(rsc/stage/{{stage.id}}/{{photo.file}}.thumb.jpg)"
            ng-click="openPopoverImageViewer('#photos', $index)"
            >
            <div>{{photo.description}}</div>
        </div>
    </div>
</div>

The directive is as follows:

app.directive('hscroller', function () {
    return {
        restrict: "A",
        link: function(scope, element, attr) {
            var pid=$(element).attr("id");
                var children = $(element).children();
                var id=$(children).attr("id");
                var firstChild = $(children[0]);
                var width = firstChild.width()*(children.length);
                console.log("openPopover hscroller: compute scroller (id="+id
                    +") width "+children.length+" children of "
                    +firstChild.width()+"px width, total="+width
                    + " (parentid="+pid+")"
                );

                $(element).css({"width":width+"px"});
        }
    };
});

While running, it sounds the directive has no children in there (a race condition with the ng-reapeat.?), the log is as follows:

[Log] openPopover hscroller: compute scroller (id=undefined) width 0 children of nullpx width, total=0 (parentid=photos)

I'm stuck with this, any idea?

Note: btw, all this is to adjust the width of the scroller element so that I could have a nice horizontal scroller on ipad device (Is there a fix in CSS?).

.hScrollable {
    overflow-x: scroll;
    overflow-y: hidden;
    -webkit-overflow-scrolling: touch;
    white-space:nowrap;
}

.scrollerContainer {
    width: 100%;
    height: @popoverScrollHeight;
    .hScrollable;
}
.scroller {
    overflow: hidden;    // this is really important to avoid vertical scrolling on devices
    height: @popoverScrollHeight;
}
Était-ce utile?

La solution

You'd propably want to write your code in the link function inside a $timeout callback.

No need to wrap element with jQuery since it's already a jquery object.

app.directive('hscroller', function ($timeout) {
    return {
        restrict: "A",
        link: function(scope, element, attr) {
            $timeout(function(){
                var pid=element.attr("id");
                var children = element.children();
                (...)
            });

        }
    };
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top