angularjs指令更改ngModel输入类型数字格式

时间:2017-10-15 20:54:02

标签: angularjs

我试图更改ngModel(input type="number")格式。如您所见,此代码在angularjs 1.2.23版本中工作良好,但在1.6.4版本中无效。任何其他解决方案?

Output must be: 25,00



var app= angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
    $scope.test=25;
})

.directive('price', function($filter) {
    return {
       restrict: 'A',
       require: '?ngModel',
       link: function(scope, element, attrs, ngModel) {
           ngModel.$formatters.push(function (value) {
                return $filter('number')(value,2);
           });
       }
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <input type="number" ng-model="test" price>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

类型为Input

number需要Number而不是String

在您的示例中,返回值为String

ngModel.$formatters.push(function (value) {
  return $filter('number')(value,2);
});

使用parseFloat()parseFloat()函数解析参数并返回浮点数。在我的方法中,我使用了step属性,该属性为0.01增加了值。

<强>的jsfiddle:

&#13;
&#13;
var app= angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
    $scope.test=25;
})

.directive('price', function($filter) {
    return {
       restrict: 'A',
       require: '?ngModel',
       link: function(scope, element, attrs, ngModel) {
           ngModel.$formatters.push(function (value) {
                return parseFloat(value);
           });
       }
    }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <input type="number" step=".01" price ng-model="test">
</div>
&#13;
&#13;
&#13;