如何从Angular指令运行一次jQuery插件

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

本文关键字:一次 jQuery 插件 Angular 指令 运行      更新时间:2023-09-26

我确信我想要实现的目标很容易,但在使用Angular两天后,我仍然停滞不前。

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();
        }
    };
});

我必须承认,jQuery对我来说太夸张了,但我很懒,想尽快开始。

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')

基本上,我所需要的只是在Angular构建了markup之后运行的插件。

您将指令添加为属性,而不是模型:

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

Angular将自动将camel大小写指令转换为以下sliderDirect->slider-direct,以便在HTML中使用。如果您希望指令应用于属性为的元素,还应该针对link函数中的element变量

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