如何用角度来评估表​​达式?

时间:2016-01-29 13:50:02

标签: javascript angularjs

我知道有一个$eval()函数可以提供像3+4, 5*4+(5+6)这样的数学结果。但是当我输入5k之类的任何东西时,我在输入字段上实现了一个东西千上模糊事件。现在我需要实现所有数学运算,如(5k +2k) ..乘以(2k*2k) ..

我们可以显示高达two小数位的输出吗?

HTML

<div ng-controller='cntrl'>
     <input type='text'  ng-model='user' ng-blur="change()"> 
     <input type='text' to-number ng-model='second'>     
</div>

控制器代码

var dict = {
  k: 1000,
  l: 100000
};
$scope.change = function(){
      var regex = /^([-+]?[0-9,]*\.?[0-9]+)([kl])$/;
      var match;
      if(angular.isString($scope.user) && (match = $scope.user.match(regex)) ) {
         $scope.user = match[1].replace(/,/g , "") * dict[match[2]];
         $scope.user = numberFilter($scope.user, 0);
      }
}

http://plnkr.co/edit/FalqWJFCqaFyvJ1xMced?p=preview

1 个答案:

答案 0 :(得分:1)

可能的答案(http://plnkr.co/edit/Uvv9zHtsAL44rIrYpsS5?p=preview):

$scope.change = function() {
    var regex = /[0-9,]*\.?[0-9]+[kl]/g;
    var match;
    if (angular.isString($scope.user) && (match = $scope.user.match(regex))) {

      angular.forEach(match, function(m){
        angular.forEach(dict, function(value, key){
          if( m.endsWith(key) ) {
            var intValue = m.replace(key, '') * dict[key];
            $scope.user = $scope.user.replace(m, intValue);
          }  
        })
      })

      $scope.user = $scope.$eval($scope.user);
      $scope.user = numberFilter($scope.user, 0);
    }

  }