FERNANDO ORTIZ FERNANDO ORTIZ - 2 months ago 8
AngularJS Question

angular directive does not work with input type = "number"

The code below works only when the input type is text, and it doesn't work when the type is number.

<div ng-app="myApp" ng-controller="myCtrl as model">
<input type="text" ng-model="cero" ng-decimal >
</div>


angular
.module("myApp",[])
.controller('myCtrl', function($scope){
var model=this;
})
.directive('ngDecimal', function ($parse) {
var linkFunction =function(scope, element, attrs){
element.bind("keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.format, {'event': event});
if(scope.cero===undefined || scope.cero===''){
scope.cero="0.",
event.preventDefault();
}else{

}
});
}
});
};
return{
restrict : 'A',
scope:{
cero: '=ngModel'
},
link: linkFunction
}
});


What I need help with is changing the type to number and still making the code work. The code is also on CodePen.

Answer

Updated pen : http://codepen.io/anon/pen/QKOVkP?editors=1011

Works with number, constraint being you cannot assign

scope.cero = "0." // string value

to a type="number" so replace it with the minimum number you want to assign, maybe

scope.cero = parseFloat("0.01")  // parseFloat("0.") won't work
Comments