2

In my application Two text boxes have

 <input type="text" ng-model="priceSlider.min" /><br/>
 <input type="text" ng-model="priceSlider.max" /><br/>

My angularjs controller is:

app.controller('MainCtrl', function($scope) {
    $scope.priceSlider       = {};
    $scope.priceSlider.min   = 100;
    $scope.priceSlider.max   = 400;
    $scope.priceSlider.ceil  = 500;
    $scope.priceSlider.floor = 0;

    $scope.$watch('priceSlider.min',function(newVal,oldVal) {
        if(isNaN($scope.priceSlider.min)) {
            console.log('naan');
            $scope.priceSlider.min=oldVal;
        }

        if($scope.priceSlider.min>$scope.priceSlider.max) {
            console.log($scope.priceSlider.min>$scope.priceSlider.max);
            console.log($scope.priceSlider.min+":"+$scope.priceSlider.max);

            var t = $scope.priceSlider.min;
            $scope.priceSlider.min = $scope.priceSlider.max;
            $scope.priceSlider.max = t;
        }
    }
});

Now most of the time the in if condition in $watch works fine but in some conditions it fails eg: If I write 200 and 300 in the two text boxes and I select the first text box and try change(to 5),the the values coming to if is 5 and 300 but the condition 5>300 if showing true... I am not able to find why this is happening . Is I'm doing anything foolish

Please check thing in the plunker.

http://plnkr.co/edit/4Wga7zCIX2udPZa6b0gI

Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
Jojo
  • 403
  • 5
  • 16
  • 1
    possible duplicate of [Javascript string/integer comparisons](http://stackoverflow.com/questions/5630123/javascript-string-integer-comparisons) – Bergi Aug 14 '15 at 09:29
  • @mohamedrias Oh yes you are right – Jojo Aug 14 '15 at 09:35

1 Answers1

3

The reason why you're getting true when you compare 5 and 300 could be it's doing a string comparison.

"5" > "300" 
>> true

So convert the value to integer and then compare. use parseInt(val, 10) or Number(val)

mohamedrias
  • 18,326
  • 2
  • 38
  • 47