我是AngularJS新手,在我的项目中多个元素中使用了一个jQuery插件(Nice)。我有下面的代码,它运行良好。
服务
.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 data-ng-app="xxx" data-nice-scroll></html>
<table class="table-responsive" data-nice-scroll></table>
....
我有更多的元素,我需要使用这个插件与不同的设置。所以我所做的是对的?或者还有其他更聪明的方法来处理这个案子?
你好,Rushenn
发布于 2015-05-24 11:47:49
您不需要服务,如果需要使用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');
}
}
}
}
}])
https://stackoverflow.com/questions/30427578
复制