Weedoze
Weedoze

Reputation: 13953

Angularjs ng-model with number input

I'm trying to retrieve an input[number] in my controller.

I found a solution which said to add a $scope.$watch on the input.

I tried it but now my number is "NaN".

<div class="offerText">
    <label class="form-inline" ng-if="!admin">What will it cost ? <input type="number" class="form-control" ng-model="estimation"/></label>      
    <label class="form-inline">Comments <textarea rows="3" cols="50" class="form-control" ng-model="comments"></textarea></label>
</div>

And In my controller

    $scope.$watch('estimation', function (val, old) {
        $scope.estimation = parseFloat(val);
    });

Thx for your help !

Upvotes: 2

Views: 1043

Answers (3)

JB Nizet
JB Nizet

Reputation: 692121

You don't need a watch. The problem here is that the input is inside an ng-if directive, which defines its own scope. The estimation is stored in the ng-if scope instead of being stored in the controller scope.

Rule or thumb: always have a dot in your ng-model.

In your controller, add

$scope.data = {};

And in the html, use

ng-model="data.estimation"

and

ng-model="data.comments"

Upvotes: 4

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

When your value is "" or null you will always get parseFloat result as NaN

$scope.$watch('estimation', function (val, old) {
    return !isNaN(val) ? parseFloat(val): 0; //considering default value is 0 
});

Other possible way would get value on change, using ng-change directive.

<div class="offerText">
    <label class="form-inline" ng-if="!admin">What will it cost ? <input type="number" class="form-control" ng-model="estimation" ng-change="changedEstimation(estimation)"/></label>      
    <label class="form-inline">Comments <textarea rows="3" cols="50" class="form-control" ng-model="comments"></textarea></label>
</div>

Controller

$scope.changedEstimation =  function(val){
   return !isNaN(val) ? parseFloat(val): 0;
}

Upvotes: 0

Raulucco
Raulucco

Reputation: 3426

Test if the new value is not undefined or null or something falsy, this happens because angular loops a few times through the watchs and the models, this process is call dirty checking

$scope.$watch('estimation', function (val, old) {
        if (!val) {
          return;
        }
        $scope.estimation = parseFloat(val);
    });

Upvotes: 0

Related Questions