2017-06-03 63 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. 
    }