问题描述:

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 ?

网友答案:

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

网友答案:

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>
网友答案:

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/

相关阅读:
Top