Search code examples
jqueryangularjsjquery-uiangularjs-directivejquery-ui-slider

Convert jQuery UI slider widget to AngularJS directive


I'm trying to build an Angular directive that creates a keyboard-accessible slider widget. I found several Angular sliders on Github, but none of them are keyboard-accessible. So, I'm trying to convert the jQuery UI slider to an Angular directive.

Here is how I'd build the widget without Angular.

HTML:

<div id="slider"></slider>
<input type="text" id="amount"/>

Javascript:

$("#slider").slider({
  min: 1,
  max: 10,
  slide: function(event, ui) {
    $("#amount").val(ui.value);
  }
});

And this is how I'd like the Angular directive to work:

<slider min="1" max="10" ng-model="sliderValue"/>
<input type="text" ng-model="sliderValue"/>

As an example, here is a jsFiddle that shows how someone converted a jQuery UI date widget to an Angular directive.

http://jsfiddle.net/xB6c2/121/

I'd like to do something similar to this for the slider widget. Thanks!


Solution

  • Here is a solution that works. Thank you to Duc Hong - his answer was instrumental in helping me to figure this out. Please let me know if there is a better way to do this.

    app.directive('slider', function() {
        return {
            restrict: 'AE',
            link: function(scope, element, attrs) {
                element.slider({
                    value: scope[attrs.ngModel],
                    min: parseInt(attrs.min),
                    max: parseInt(attrs.max),
                    step: parseFloat(attrs.step),
                    slide: function(event, ui) {
                        scope.$apply(function() {
                            scope[attrs.ngModel] = ui.value;
                        });
                    }
                });
            }
        };
    });