简体   繁体   中英

How to run a jQuery plugin once from a Angular Directive?

I am sure what I am trying to achieve is easy, but having spent 2 days with Angular I'm still stuck.

JS

var app = angular.module('mays', []);

app.controller('Slider', function ($scope) {
    $scope.sliderItems = [
        {
            number: 1,
            title: 'Goals',
            text: 'We did stuff and stuff'
        }
    ];
});

//A directive is what I believe I need.


//JS Plugin

app.directive('sliderDirect', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
             $('.slider').royalSlider();
        }
    };
});

I must admit, jQuery for me is overkill, but I'm lazy and want to start things quickly.

HTML/Jade

ul(class='slider royalSlider rsDefault', ng-repeat='item in sliderItems', ng-model='sliderDirect')
       li
           h1 {{item.title}}
               p {{item.text}}
               img(ng-src='/img/news/{{item.number}}.jpg')

Basically, all I need is the plugin to run once Angular has built up the markup .

You add the directive as an attribute, not a model:

ul(class='slider royalSlider rsDefault', ng-repeat='item in sliderItems', slider-direct)

Angular will automatically convert camel case directives to the following sliderDirect -> slider-direct for use in the HTML. You should also be targeting the element variable in the link function if you want the directive to apply to the element with the attribute:

return {
    restrict: 'A',
    link: function(scope, element, attrs) {
         $(element).royalSlider();
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM