我是AngularJS的新手,在我的项目中使用了多个元素的jQuery插件(Nice Scroll)。我有以下代码,它运行良好。
服务
.service('nicescrollService', function() {
var ns = {};
ns.niceScroll = function(selector, color, cursorWidth) {
$(selector).niceScroll({
cursorcolor: color,
cursorborder: 0,
cursorborderradius: 0,
cursorwidth: cursorWidth,
bouncescroll: true,
mousescrollstep: 100
});
}
return ns;
})
指令
.directive('niceScroll', ['nicescrollService', function(nicescrollService){
return {
restrict: 'A',
link: function(scope, element) {
//Scrollbar for HTML(not mobile) but not for login page
if (!$('html').hasClass('ismobile')) {
if (!$('.login-content')[0]) {
nicescrollService.niceScroll('html', 'rgba(0,0,0,0.3)', '5px');
}
//Scrollbar Tables
if ($('.table-responsive')[0]) {
nicescrollService.niceScroll('.table-responsive', 'rgba(0,0,0,0.5)', '5px');
}
//Scrill bar for Chosen
if ($('.chosen-results')[0]) {
nicescrollService.niceScroll('.chosen-results', 'rgba(0,0,0,0.5)', '5px');
}
}
}
}
}])
HTML
<html data-ng-app="xxx" data-nice-scroll></html>
<table class="table-responsive" data-nice-scroll></table>
....
我需要更多元素来使用此插件并使用不同的设置。那我正在做的是对的吗?或者Angular还有其他更智能的方法来处理这种情况吗?
此致 Rushenn
答案 0 :(得分:1)
你不需要服务,如果你需要使用Jquery选择器,最好在指令的链接属性中使用它,如:
.directive('niceScroll', [function(){
return {
restrict: 'A',
link: function(scope, element) {
scope.niceScroll = function(selector, color, cursorWidth) {
$(selector).niceScroll({
cursorcolor: color,
cursorborder: 0,
cursorborderradius: 0,
cursorwidth: cursorWidth,
bouncescroll: true,
mousescrollstep: 100
});
};
//Scrollbar for HTML(not mobile) but not for login page
if (!$('html').hasClass('ismobile')) {
if (!$('.login-content')[0]) {
scope.niceScroll('html', 'rgba(0,0,0,0.3)', '5px');
}
//Scrollbar Tables
if ($('.table-responsive')[0]) {
scope.niceScroll('.table-responsive', 'rgba(0,0,0,0.5)', '5px');
}
//Scrill bar for Chosen
if ($('.chosen-results')[0]) {
scope.niceScroll('.chosen-results', 'rgba(0,0,0,0.5)', '5px');
}
}
}
}
}])