【问题标题】:Integrating jQuery plugin calls inside AngularJS Directives在 AngularJS 指令中集成 jQuery 插件调用
【发布时间】:2017-06-03 11:49:13
【问题描述】:

我一直致力于将一个普通的静态网站转换为一个 AngularJS 网站 - 只是为了提高我在这方面的技能。

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

现在在主页上,我使用 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>

谁能帮帮我?我已经尝试了几种方法,但仍然没有显示和工作。

【问题讨论】:

  • 我也尝试过这样做:$(element).owlCarousel(scope.$eval(attrs.featuredSlider)); 仍然没有成功的机会!

标签: javascript jquery angularjs plugins directive


【解决方案1】:

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

【讨论】:

  • 我怎样才能做到这一点? HomeController 仅具有页面内 ng-repeat 上的数据数组。你能帮我解决这个问题吗?我严重卡在这部分。
【解决方案2】:

以这种方式创建依赖项: f.e:

//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.
    } 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    相关资源
    最近更新 更多