如何从angularjs指令访问内部元素?

时间:2014-05-15 00:55:20

标签: angularjs angularjs-directive

我想计算元素滚动条的宽度,就像孩子的数量x第一个孩子的宽度一样。 为此,我设计了一个指令hscroller。

HTML如下:

<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>

该指令如下:

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"});
        }
    };
});

在跑步的时候,听起来这个指令里面没有孩子(一个有ng-reapeat的竞争条件。?),日志如下:

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

我坚持这个,任何想法?

注意:顺便说一下,这一切都是为了调整滚动条元素的宽度,这样我就可以在ipad设备上有一个漂亮的水平滚动条(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;
}

1 个答案:

答案 0 :(得分:1)

您可能希望在$ timeout回调中的链接函数中编写代码。

不需要用jQuery包装元素,因为它已经是一个jquery对象了。

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

        }
    };
});