2017-04-24 72 views
0

我試圖將正常的jQuery自己的旋轉木馬轉換爲Angular指令。它不適用於我,顯示一些角度錯誤,我無法找到問題所在。自定義貓頭鷹旋轉木馬指令

控制器

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

HTML(玉)

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

回答

1

你的問題是在這條線$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:使用範圍綁定一個礙事的選項。 (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-*前綴。

更多信息: