the context: I am developing a mobile version of my app. I want a user to be able to enter numeric fields with their numeric keybord of their phone/tablet. AngularJS makes input fields with type = "number" unreachable for any non-integer data (which is any, because input is a string).
the idea: I want to make a directive that will somehow (using $watch or $parsers or any other ancient sorcery) convert input string to number.
the issue: My directive does not trigger changes of $watch when I type anything in the input field. But when I change scope field from my cotroller $watch is triggered as planed.
controller:
// code minimized and omitted for clarity
.controller('carController', ['$scope', function ($scope) {
$scope.car = {
power : null,
// other fields
}
}]);
directive
angular.module('numeric', []).directive('numeric', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel'
},
link: function (scope, element, attrs, ngModelCtrl) {
// parsers does not affect anything
ngModelCtrl.$parsers.push(function(value) {
return parseInt(value);
});
// watcher does not watch
scope.$watch('model', function(newVal, old) {
if (typeof newVal == 'string') {
scope.car.power = parseInt(newVal);
}
}, true);
}
};
});
html
<div ng-controller="carController">
<input
ng-model="car.power"
numeric
name="power"
type="number"
pattern="[0-9]">
</div>
Here is a fiddle that demonstrates such behavior http://jsfiddle.net/xo94sw7m/1/
the question: what am I missing and how to make directive work as planned?
What I have tried: using $formatters-$parsers,using different approaches to $watch (using scope:false, isolated scope, trying to watch scope changes using attrs and etc), nothing seems to work so far
<input type="number">fully supports floatsparseFloat()and that is just bad copy-paste, I replaced in withparseInt(). But it does not make any difference -type=numberwill block .... wait. It seems that u were right, i have just deleted my directive and input is accepted jsfiddle.net/aqkobhux I don't understand what originally was wrong then...pattern="[0-9]"attribute... Thank you for your help!