Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 202
user1775367 Avatar asked Oct 25 '12 20:10

user1775367


1 Answers

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.

like image 63
jaime Avatar answered Oct 22 '22 11:10

jaime