0

I have the an input field where only positive numbers are allowed.

<input id="charge-hours" type="text" class="charge-position-hours-edit" placeholder="0" ng-model="charge.hours">

How to control the setting of ng-model.

I would like write a precondition before the value set in the scope. Something like

$scope.precondition = function (value) {
        if (!isNan(value)) {
          $scope.value=value;
        }else{
          //do nothing
        }
      }

Is this possible in javascript/angularjs? In jave there would be setter for that.

EDIT

My Question was not clear enough.

I really want only positive numbers are typable in the input field, and only positive numbers should be bound to the ng model of angularjs.

Is there a way to save the oldValue if I use ng change? Then I may write something like

if (condition===true) //ok 
else $scope.value=oldValue;
Rudolf Schmidt
  • 2,345
  • 5
  • 21
  • 28
  • Just look at the ["custom validation" part of the angularjs form documentation](https://docs.angularjs.org/guide/forms#custom-validation) – Patrick Ferreira Jun 02 '14 at 14:17

2 Answers2

0

if your problem is to make sure the value is an integer and positive you can use HTML5 to validate this.

Check this link number.

To validate the number you can use the ng-change directive to control it, if you want more control use ng-keyup.

Also consider looking at "custom validation" part of the angularjs form documentation – just like Patrick Ferreira sugested.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
1st4ck
  • 1,267
  • 11
  • 11
-1

Try this:

<input id="charge-hours" type="text" class="charge-position-hours-edit" placeholder="0" ng-model="charge.hours" ng-change="precondition()">

source

avidenic
  • 653
  • 7
  • 17
  • [You can't think like in jQuery](http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background) and listen for user actions ... AngularJS provides lots of tools for [that kind of things](https://docs.angularjs.org/guide/forms#custom-validation) – Patrick Ferreira Jun 02 '14 at 14:20