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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With