AngularJS:为小数点创建自定义过滤器



我正在尝试将下面的JS代码转换为可重用的AngularJS过滤器

var a = 1.1230000,
    b = a.toFixed(15).replace(/.?0+$/, "");  // ==> 1.123

我已经创建了以下代码(AngularJS)

  angular.module('myApp.filters', []).filter('fixed', [function () {
    return function(input) {
      return input = input.toFixed(15).replace(/.?0+$/, "");
    };
  }]);

并对模块

调用新的过滤器
var myApp = angular.module('myApp', ['fixed']);

但是显示错误: [$injector:modulerr] http://errors.angularjs.org/1.2.16/$injector/modulerr?p0=myApp&p1=%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%.........

我错过了什么,我为任何错误感到抱歉。谢谢你的帮助。

更新——JSBIN URL添加

你不需要注入已经是模块一部分的组件。myApp。myApp.

是的,您没有将filters模块注入您的myApp模块。像这样修改你的代码,它将为你工作

   var myApp = angular.module('myApp', ['filters']);//inject your filters Module into myApp Module

   angular.module('filters', []).filter('fixed', function () { //change module name as filters
    return function(input) {
      return input.toFixed(15).replace(/0+$/, "");
    };
  }); 

更新本

solution2

根据你的代码,你可以这样修改

var myApp = angular.module('myApp', ['myApp.filters']);//inject myApp.filters into your myApp Module. 

剩余的代码像魅力一样工作…

jsBin for Solution2

最新更新