2017-06-03 61 views
0

我一直致力于将普通的静态网站转换为AngularJS网站 - 以提高我的技能。在AngularJS指令中集成jQuery插件调用

到目前为止,我已经完成了路线,看起来不错。

现在,在主页上,我使用ng-repeat指令加载滑块图像,并且它也在工作。但我注意到滑盖本身并没有发挥其应有的功能。所以我发现我在一个单独的js文件上创建的jQuery函数根本没有加载。而且我还发现,这可以通过在指令中集成插件调用来实现。

所以,我做了这个:

app.directive('featuredSlider', [function() { 
return { 
    restrict: 'A', 
    link: function(scope, elem, attrs) { 
     $(elem).owlCarousel({ 
      itemsCustom: [ 
       [0, 1], 
       [600, 2], 
       [1200, 4] 
      ], 
      autoPlay: 3000 
     }); 
    } 
};}]); 

我使用OwlCarousel滑块和它没有被使用一个我在上面做了触发。

顺便说一句,这是我的控制器的样子如何:

app.controller('HomeController', function($scope) { 
$scope.featuredImages = []; } 

featuredImages上述阵列具有滑块的图像的URL。

然后,这是滑块所在的部分。

<div class = "featured owl-carousel owl-theme featured-slider"> 
    <div class = "item" ng-repeat = "featured in featuredImages"> 
     <img ng-src = "{{featured.img}}" /> 
    </div> 
</div> 

任何能帮助我的人?我尝试了几种方法,但仍然没有显示和工作。

感谢先进!

+0

我也试着这样做: '$(element).owlCarousel(scope。$ eval(attrs.featuredSlider));' 仍然没有机会使它工作! – alleycat

回答

0

使用指令的控制器并将第三方库作为服务,以便您可以在指令控制器中注入依赖项。

+0

我该如何做到这一点? ** HomeController **只有在页面内** ng-repeat **的数据数组。 你能帮我解决这个问题吗?我被严重困在这个部分。 – alleycat

0

以这种方式创建的依赖关系: FE:

//Import moment.js into your page as always 
<script type="text/javascript" 
     src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.js"/> 

//Before your main app module is declared, declare a momentjs module 
angular.module('momentjs',[]) 
    //And on the momentjs module, declare the moment service that we want 
    // available as an injectable 
    .factory('moment', function ($window) { 
    if($window.moment){ 
     //Delete moment from window so it's not globally accessible. 
     // We can still get at it through _thirdParty however, more on why later 
     $window._thirdParty = $window._thirdParty || {}; 
     $window._thirdParty.moment = $window.moment; 
     try { delete $window.moment; } catch (e) {$window.moment = undefined; 
     /*<IE8 doesn't do delete of window vars, make undefined if delete error*/} 
    } 
    var moment = $window._thirdParty.moment; 
    return moment; 
    }); 

,然后把该指令以这种方式来分配自己的控制器:

angular.module("example").directive('exampleDirective', [function() { 
    return {    
     templateUrl: 'path', 
     restrict: 'AE', 
     transclude:true, 
     controller: 'myDirectiveController' 
    }; 
}]).controller('myDirectiveController',myDirectiveController); 


function myDirectiveController($scope , $element, $attrs, moment) { 
     //and now you can use this thir party library in the directive controller. 
    }