user1775367
user1775367

Reputation: 71

Why is an input of type="number" not showing updates to its bound value?

A set of HTML input controls are bound to testVar:

<div ng-app>
    <div ng-controller="TestCtrl">
        <input type="text" ng-model="testVar">
        <input type="number" min="1" max="10" ng-model="testVar">
        <input type="range" min="1" max="10" ng-model="testVar">
        <button ng-click="testVar = 5">set to 5</button>              
    </div>
 </div>

Initially all the input controls show this value as expected, but the type="number" input becomes blank when testVar is changed via the type="range" or type="text" inputs. Setting the value of testVar programmatically results in the expected behaviour: all the inputs show the updated value.

The issue is demonstrated by this simple case: http://jsfiddle.net/7cbYp/

Why is this happening, and how can it be fixed?

Upvotes: 7

Views: 2113

Answers (2)

Mahes
Mahes

Reputation: 4135

input[type=range] converts the model datatype to string, which cannot be displayed in input[type=number].

similar problem with solution here.

Angular Data Binding - Input type="number"

Upvotes: 0

jaime
jaime

Reputation: 42031

A quick fix would be to create a directive and watch for changes in the model and the HTML item itself

HTML

<input type="number" min="1" max="10" fix="testVar">

JS

var App = angular.module('App', []);
App.directive('fix', function(){
    return{
        link: function(scope, elem, attrs){
            scope.$watch(attrs.fix, function(v){
                if(typeof v === 'string') v = parseInt(v, 10);
                elem.val(v);
            });
            elem.bind('change', function(){ 
                scope[attrs.fix] = elem.val(); 
                scope.$digest();
            });
        }
    };
});

I have only tested it on Chrome and it works.

jsfiddle: http://jsfiddle.net/jaimem/HLnqt/3/

Note: there must be a cleaner way to do this.

Upvotes: 3

Related Questions