2

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 !

1
  • when value is "" or null conversion will obiviously parseFloat would be always NaN Commented Mar 26, 2015 at 13:52

3 Answers 3

4

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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);
    });

1 Comment

console.log("ESIMATION : " + $scope.estimation); It says "undefined"
0

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;
}

2 Comments

console.log("ESIMATION : " + $scope.estimation); It says : "Undefined"
on initial it will be undefined, after changing value you can get the changed val..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.