Flo-Schield-Bobby Flo-Schield-Bobby - 6 months ago 36
AngularJS Question

How to add a custom callback on-slide for UI sliders using Angular directives?

I'm beginning with Angular.js directives, and in any application, I'm using jQuery UI sliders.

What I would to do is to execute a custom callback on the slide event of these sliders, depending of the slider, because I have more than one in the page.

I made a JSFiddle here:

And basically, this is the directive I "wrote", inspired of some Google Discussion threads that I found.


<section id='app'>
<aside id='settings' ng-controller='SettingsCtrl'>
<form name='settings-form' method='post' action='#' ng-submit='generate()'>
<h4 class='settings-title'>Settings</h4>
<h5>Quality <span id='quality-value' class='info'>1</span></h5>
<div id='quality' class='slider slider-range' min='1' max='3' step='1' value='1' ui-slider></div>
<h6 id='quality-label' class='label info'>Take care of this point: increase the quality level needs a lot of resources from your computer, it may slow it down or crash this website.</h6>
<h5>rotation <span id='rotation-value' class='info'>0</span></h5>
<div id='rotation' class='slider slider-range' min='0' max='360' step='1' value='0' ui-slider></div>
<input type='submit' id='submit' name='submit' value='Hyperlapse it !' />


angular.module('myApp.directive', []).directive('uiSlider', function () {
return function(scope, element, attrs) {
value: parseInt(attrs.value),
min: parseInt(attrs.min),
max: parseInt(attrs.max),
step: parseInt(attrs.step),
slide: function (e, ui) {
// So here I can get the value with ui.value,
// But how to execute a custom callback, depending on the slider ?
// For instance, I am trying to update an element with the value
// $('#quality-value').text(ui.value) for the quality slider
// $('#rotation-value').text(ui.value) for the rotation slider.

I would appreciate any suggestion/advice on this point !


Take a look at http://jsfiddle.net/cJRCW/

A quick solution is to pass the name of a callback as an attribute to the directive, with the assumption this will be a function available in the local scope.

In your template:

<div id='quality' class='slider slider-range' min='1' max='30' step='1' value='1' callback='callback1' ui-slider></div>

In your controller:

$scope.callback1 = function() {
    console.log('callback1 called');   

$scope.callback2 = function() {
    console.log('callback2 called');

In your directive:

slide: function (e, ui) {