Search code examples
angularjsangular-ngmodel

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 !


Solution

  • 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"