1

Controller:

angular.module('myApp', [])
    .controller('MainCtrl', function($scope) {
        $scope.d = { v1: '100', v2: '20' };
    });

Template:

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
      1: <input type="text" ng-model="d.v1" />
      2: <input type="text" ng-model="d.v2" />
      <h4>{{d.v1}} &lt; {{d.v2}} = {{d.v1 < d.v2}}</h4>
  </div>
</div>

http://jsfiddle.net/GDfxd/292/

This example incorrectly shows that 100 is less than 20. Any advice how to make this comparison numeric ?

3
  • 1
    because they are strings not numbers, you need to convert before compare jsfiddle Commented Feb 16, 2017 at 19:51
  • 1
    Make type="number" Commented Feb 16, 2017 at 19:52
  • @Jag try entering some numbers in inputs, they will be string type again Commented Feb 16, 2017 at 20:08

3 Answers 3

1

the type of your variable is "text" you have to change it to "number" to get the right result.

Sign up to request clarification or add additional context in comments.

Comments

0

All that you need is to compare numbers instead of strings

Here is the working snippet:

angular.module('myApp', [])
    .controller('MainCtrl', function($scope) {
        $scope.d = { v1: 100, v2: 20 };
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MainCtrl">
      1: <input type="text" ng-model="d.v1" />
      2: <input type="text" ng-model="d.v2" />
      <h4>{{d.v1}} &lt; {{d.v2}} = {{d.v1 < d.v2}}</h4>
  </div>
</div>

Comments

0

Try this, I just added an Eval function and left everything else the same!

Controller:

angular.module('myApp', [])
    .controller('MainCtrl', function($scope) {
        $scope.d = { v1: '100', v2: '20' };
        $scope.eval = function() {
           return (parseInt($scope.d.v1, 10) < parseInt($scope.d.v2, 10));
        }
    });

Template:

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
      1: <input type="text" ng-model="d.v1" />
      2: <input type="text" ng-model="d.v2" />
      <h4>{{d.v1}} &lt; {{d.v2}} = {{eval()}}</h4>
  </div>
</div>

http://jsfiddle.net/jc4vvp86/2/

Comments

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.