2

I want to create a range slider with an input field to directly type the value (like in jQM: http://demos.jquerymobile.com/1.4.4/slider/).

My directive looks like this:

app.directive("mySlider", [function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            id: "@?",
            min: "@",
            max: "@",
            step: "@?",
            value: "=ngModel"
        },
        template: "" +
            "<div class='my-sliderWrap'>" +
                "<input type='number' min={{min}} max={{max}} step={{step}} value={{value}} ng-model=value>" +
                "<input type='range' min={{min}} max={{max}} step={{step}} value={{value}} ng-model=value>" +
            "</div>",
        link: function ($scope, $element, $attrs) {

            //some logic here
        }
    }
}]);

Well, this works nice when I'm changing the value of the number input. The slider moves and the value attributes both are updated. As soon as I move the slider directly, both value attributes still update but the text of my number input gets cleared somehow and set to its minimum.

Have I made some mistake within the template or with the data binding?

1 Answer 1

2

Solved, according to this answer on the same issue:

https://stackoverflow.com/a/24808152/2577116

Summary: It seems that the HTML5 range input does not return a number but a string. Assigning this string to the number input causes the same to clear itself, as, who would think of that, it will expect a number...

As solution we just need to convert the returned string value into a number. I do it with parseFloat() for example:

$scope.$watch('value',function(newValue) {
  $scope.value = parseFloat(newValue); //or Number(newValue); or parseInt(newValue);
});

This logic can just be inserted into the link function. Done.

Not very nice, but easy workaround.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.