我尝试将普通的 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/