0

I tried to convert the normal jQuery own carousel into Angular Directive. It doesn't work for me, show some angular errors which I couldn't find what is the issue.

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

Directive

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

ERROR

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

Foonation
  • 215
  • 3
  • 17

1 Answers1

1

Your problem is at this line $scope.$eval($(el).attr('data-options'));. This produce a parse syntax error. You have two options to fix it:

OPTION 1: get the options from attrs parameter of link directive function. (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
    }
  }
});

OPTION 2: get the options using scope one way binding. (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
    }
  }
});

As you can see I'm getting the html data-options attribute as just options. That's because angularjs directives will ignore data-* prefix in all HTML elements and attributes names.

More info:

Community
  • 1
  • 1
The.Bear
  • 5,621
  • 2
  • 27
  • 33