在AngularJS中使用过滤器onclick进行毫米-英寸转换器

mm - inches converter using a filter onclick in AngularJS

本文关键字:转换器 AngularJS onclick 过滤器      更新时间:2023-09-26

我有一个UI,需要输入宽度和高度的尺寸。

我有2个按钮,1为"毫米"和1为"英寸"。当按下这些按钮时,它需要首先将活动类从默认的(mm)更改为英寸(这是工作的)。

它还必须将字段图标从'mm'更新为'inch '(这正在工作)。

我正在努力使用我的过滤器,我需要它在点击上工作-我已经在我的控制器中有一个函数,通过更新$scope.activeUnit = currentUnit来运行点击并更新按钮和字段图标上的活动类。过滤器代码如下:

.filter('convertUnits', function() {
    return (function (unit) {
        if (unit == 'inches') {
            return Math.floor(input * 0.0393701);
            console.log('hello-inches');
        }
        else if (unit == 'mm') {
            return Math.floor(input / 0.0393701);
            console.log('hello-mm');
        }
    });
})

点击事件运行的函数如下:

$scope.changeUnits = function(unit) {
        $scope.activeUnit = unit
        console.log(unit);
        // Run filter code here?
        // Update all mm to inches on the view and vice versa
    }

我希望这个在我的控制器上的on-click函数中运行,并将视图上的任何尺寸转换为英寸,然后当mm被单击以转换回方式。

如果有任何帮助,我将不胜感激。

activeUnit作为参数传递到模板中的过滤器应该工作对吗?你试过吗?改变activeUnit应该通过绑定自动更新值。

<span ng-bind="length | convertUnits : activeUnit"></span>
<span>{{length | convertUnits : activeUnit}}/span>

您的自定义过滤器缺少一个参数。此外,console.log返回后将不工作。


.filter('convertUnits', function() {
    return (function (input, unit) {
                      ----^

但是你在模型中保持值不变,只是改变单位,这可能会令人困惑。

value = 10
unit = mm
value = 10
unit = inches

除非您决定该值将始终在mminches中,否则它可能是错误的和令人困惑的数据。

如果你能描述你最初的需求,事情可能会更清楚。
  1. 你只是显示一个固定的值,用户可以通过切换单位查看?
  2. 你是否有一些输入字段,用户可以在任何单位输入值?