javascript - AngularJS: avoid using $timeout to wait for image loading completion -
i'm trying create own image carousel angularjs directive; want keep lightweight , unopinionated possibile, thought i'd create <carousel></carousel>
wrapper set of <img>
elements, so:
<carousel> <img ng-repeat="image in images" ng-src="{{image.src}}" alt=""/> </carousel>
what directive create <div class="carousel">
element images transcluded. now, still haven't coded part images slide or fade in/out cause there's 1 issues i'd out of way first: want assign carousel , images therein same height (computed height of shortest image) avoid carousel changing height when taller image gets displayed, or avoid cropping image in case carousel had fixed height.
so jotted down this jsfiddle demonstrate, far best solution found compute heights of transcluded images relies on 2 nested $timeout
s 100-ms delay. looks me more hack anything.
wondering if there's "proper" way accomplish in angularjs. cheers.
p.s. on side note, dislike fetching root element of directive's template, <div class="carousel">
in case, using element.children()
... there no easy way reference in angularjs? looked around no dice.
you need write 1 more directive intimate angular code ng-repeat rendered img
tags on add listener event set height , width of element on load
of image.
directive
.directive("carousel", ["$timeout", function ($timeout) { return { restrict: "e", transclude: true, template: "<div class=\"carousel\" ng-transclude></div>", link: function (scope, element, attrs) { var div = element.children(); scope.$on('ngrepeatdone', function () { element.find('img').on('load', function () { var images = div.children(); var minheight = math.min.apply(null, _.pluck(images, "height")); angular.foreach([div, images], function (e) { e.css({ height: minheight + "px" }); }); scope.$apply(); }); }); } } }])
ngrepeatedone
.directive('mypostrepeatdirective', function () { return function (scope, element, attrs) { if (scope.$last) { scope.$emit('ngrepeatdone') } }; });
Comments
Post a Comment