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

  1. Define directive in ng-repeat section
  2. Wait for last element to be clone
  3. 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

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

About Author

Author Image
Chandan Lunthi

Chandan is the self-motivated person and has expertise in technologies. Chandan likes to sign and MMA fighter.

Request for Proposal

Name is required

Comment is required

Sending message..