How to apply jquery after AngularJS partial template is loaded

后端 未结 7 2359
青春惊慌失措
青春惊慌失措 2020-12-13 10:28

I have a simple website that implements jQuery in order to create a Slider with some images in the Index.html top banner.

Now, I want to use AngularJS

相关标签:
7条回答
  • 2020-12-13 11:11

    The other provided answers will work, but they are bound to controllers, and therefore not as scalable and reusable.

    To do it the real "Angular" way as mentioned in the comments, you should be using a directive. The benefit to this is that you're able to create several instances with the same code, and can pass in attributes to the directive logic to "customize" the directive. Here's a sample of a way I've used it using bxSlider plugin:

    JS:

    app.directive('slider',  ['$rootScope', function($rootScope) {
    return {
        restrict: 'EA',
        templateUrl: '/path/to/template',
        link: function(scope, iElement, attrs) {
            //attrs references any attributes on the directive element in html
    
            //iElement is the actual DOM element of the directive,
            //so you can bind to it with jQuery
            $(iElement).bxSlider({
                mode: 'fade',
                captions: true
            });
    
            //OR you could use that to find the element inside that needs the plugin
            $(iElement).find('.bx-wrapper').bxSlider({
                mode: 'fade',
                captions: true
            });
    
           }
        };
    }]);
    

    HTML:

    <div slider some-attibute="some-attribute"></div>
    

    And inside your directive template you could have the slider wrapper and slides, which you could build dynamically using ng-repeat bound to scope data.

    I'd recommend reading this excellent article by Dan Wahlin about creating custom directives and how to fully harness they're power.

    0 讨论(0)
提交回复
热议问题