javascript - 自定义猫头鹰轮播指令

标签 javascript jquery angularjs

我尝试将普通的 jQuery 自己的轮播转换为 Angular Directive。它对我不起作用,显示一些 Angular 错误,我找不到问题所在。

Controller

$scope.defaultsCarousel = {
  'items': 4,
  'itemWidth': 300,
  'itemsDesktop': [1260, 3],
  'itemsTablet': [930, 2],
  'itemsMobile': [620, 1],
  'navigation': true,
  'navigationText': false
};

HTML( Jade )

custom-carousel(data-options="{{ defaultsCarousel }}", productid="#pl-1")

指令

myApp.directive('customCarousel', function(){
 function nextSlide(e) {
    e.preventDefault();
    e.data.owlObject.next();
 };

 function prevSlide(e) {
    e.preventDefault();
    e.data.owlObject.prev();
 };

 return{
    restrict: 'E',
    scope: {},
    link: function($scope, el, attrs){
        var options = $scope.$eval($(el).attr('data-options'));
        var product_id = attrs.productid;
        console.log(product_id);
        $(product_id).owlCarousel(options);
        var owl = $(product_id).data('owlCarousel');
        $(product_id).parent().find('.slide-control.right').on('click', {owlObject: owl}, nextSlide);
        $(product_id).parent().find('.slide-control.left').on('click', {owlObject: owl}, prevSlide);
     }
}

错误

Syntax Error: Token '{' invalid key at column 2 of the expression [{{] starting at [{4}].

最佳答案

您的问题出在这一行$scope.$eval($(el).attr('data-options'));。这会产生解析语法错误。您有两种选择来修复它:

选项 1:从链接指令函数的 attrs 参数中获取选项。 (PLUNKER)

app.directive('customCarousel', function() {
  return {
    restrict: 'E',
    link: function(scope, el, attrs) {

      var options = angular.fromJson(attrs.options);
      var product_id = attrs.productid;

      //..Rest of your logic
    }
  }
});

选项 2:使用范围单向绑定(bind)获取选项。 (PLUNKER)

app.directive('customCarousel', function() {
  return {
    restrict: 'E',
    scope: {
        options: '@',
        productid: '@'
    },
    link: function(scope, el, attrs) {

      var options = angular.fromJson(scope.options);
      var product_id = scope.productid;

      //..Rest of your logic
    }
  }
});
<小时/>

如您所见,我将 html data-options 属性视为 options。这是因为 angularjs 指令将忽略所有 HTML 元素和属性名称中的 data-* 前缀。

更多信息:

关于javascript - 自定义猫头鹰轮播指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43599025/

相关文章:

javascript - 如何使用 jquery 中止所有待处理的 ajax 请求的列表?

javascript - 打印时如何计算位置固定div标签的数量?

angularjs - Angular 指令未在 ES6 中编译

javascript - JSDoc : Define allowed values of parameter which has string type

javascript - 有没有什么很酷的方法来使用惰性求值序列来定义/计算 PI?

javascript - React 16 中生命周期钩子(Hook)贬值的主要原因

javascript - 在 React-Native 中导航

javascript - 使用 Javascript 进行基本授权 API 登录(CORS?)

angularjs - 使用链接更改 ng-switch

angularjs - 使用 Ant Design 和 Moment Js,我仍然无法弄清楚如何使用日期对列进行排序?