jQuery Swiper script to run after Ng-Repeat elements are loaded

后端 未结 3 1343
甜味超标
甜味超标 2021-02-19 04:36

I\'m making a web app using AngularJS, jQuery, HTML, CSS and Bootstrap, and I would like to pick some image links from my JSON that is located in an Apache2 server and use them

3条回答
  •  爱一瞬间的悲伤
    2021-02-19 05:41

    Before getting into how to make this work, most of these types of jQuery plugins don't work well with angular since they make modifications to the DOM that angular doesn't know about.

    That being said, the trick is deferring the invocation of the jQuery plugin until after Angular has rendered the DOM.

    First, put your swiper plugin into a directive:

    .directive('swiper', function($timeout) {
        return {
            link: function(scope, element, attr) {
                //Option 1 - on ng-repeat change notification
                scope.$on('content-changed', function() {
                    new Swiper(element , {
                        direction: 'horizontal',
                        pagination: '.swiper-pagination',
                        paginationClickable: true);
                }
                //Option 2 - using $timeout
                $timeout(function(){
                    new Swiper(element , {
                        direction: 'horizontal',
                        pagination: '.swiper-pagination',
                        paginationClickable: true);
                });
    
            }
        };
    })
    

    For Option 1, you need a modified isLoaded directive

    myApp.directive('isLoaded', function (){
    
       return{
         scope:false, //don't need a new scope
         restrict: 'A', //Attribute type
         link: function (scope, elements, arguments){ 
    
            if (scope.$last) {
                scope.$emit('content-changed');
                console.log('page Is Ready!');
            }
         }   
       }
    })
    

    Finally, your markup (note the change from isLoaded to is-loaded....this is probably the reason you weren't seeing the notification).

    As mentioned, most jQuery plugins that do carousel functionality don't handle changes to the DOM (i.e new elements) very well. Even with both options, you may see unexpected things if you change your model after the ng-repeat is first rendered. However, if your model is static, this should work for you. If your model changes, then you might want to search for a more "angular" carousel directive.

提交回复
热议问题