Initialize jquery plugins after ngrepeat
Posted By : Chandan Lunthi | 25-Jun-2015
As angular is relatively new technology compared to jquery so there are less number of plugins and libraries are available for this. Jquery already have vast number of plugins like carousel, chat service etc. So users wants to use these already built plugins in to angular. Method of using these things in angular is very easy, you just have to create an angular directive and define it to container where you want to initialize. But when this condition matches with ng-repeat in angular some times it causes problem like directive excuted before ng-repeat finishes. That causes breaking of content, distorted style , semi styled thing. Then simply solution of this problem is to initilize directive after ng-repeat finishes.
Method
- Define directive in ng-repeat section
- Wait for last element to be clone
- Initialize directive then to it parent
A simple code for the directive is here
.directive('CarouselItem', [function() { return { restrict: 'A', //transclude: false, link: function(scope, element) { // wait for the last item in the ng-repeat then call init if(scope.$last) { $(element.parent()).Carousel({ intaillizing parameters goes here }) } } }; }])
Example using Owl Carousel
- Define directive in ng-repeat section
<div ng-repeat="a in a" jquery-item>
Code here........
</div>
2. Directive code
.directive('jqueryItem', [function() { return { restrict: 'A', //transclude: false, link: function(scope, element) { // wait for the last item in the ng-repeat then call init if(scope.$last) { $(element.parent()).owlCarousel({ items : 4, pagination : false, navigation : true, autoPlay: false, stopOnHover: true, touchDrag : true, mouseDrag : true, rewindNav:false, lazyLoad : true, autoWidth:true, navigationText : ["<i class='glyphicon glyphicon-menu-left'></i>","<i class='glyphicon glyphicon-menu-right'></i>"] }) } } }; }])
So this how we can solve the problem comes with jquery plugins in angular ng-repeat
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Chandan Lunthi
Chandan is the self-motivated person and has expertise in technologies. Chandan likes to sign and MMA fighter.