Tuesday 15 March 2011

angularjs - How to create a directive to only number only fields without ng model -



angularjs - How to create a directive to only number only fields without ng model -

i using angular directive allow numeric input in text box. here jsfiddle : http://jsfiddle.net/vfshx/673/

this works. required ng model, issue have table generate on-fly , each row has numeric field need utilize directive.

now since each of field in row not have ng model not work.

please advice.

i think directive tied model, it's never thought directive know model, took main thought angularjs: how allow number (digits , decimal point) typed in input?

var app = angular.module('myapp', []); app.controller('mainctrl', function($scope) { }); app.directive('validnumber', function() { homecoming { require: '?ngmodel', link: function(scope, element, attrs, ngmodelctrl) { if(ngmodelctrl) { ngmodelctrl.$parsers.push(function(val) { //this stop adding inputs aren't numbers, can alter impact validity var clean = val.replace( /[^0-9]+/g, ''); if (val !== clean) { ngmodelctrl.$setviewvalue(clean); ngmodelctrl.$render(); } homecoming clean; }); } else { element.bind('keypress', function(event) { //your logic here, not sure if want ignore or add together or whatever want without model, place var newval = element.val() + string.fromcharcode(event.keycode); //check if newval ok , set validity }); } }; });

another approach force $parsers validity check instead of replacing value:

ngmodel.$parsers.unshift(function(value) { var valid = angular.isnumber(value); ngmodel.$setvalidity('isnumber', valid); homecoming valid ? value : undefined; });

hope helps.

angularjs

No comments:

Post a Comment