我的 UI 需要输入宽度和高度的尺寸。
我有 2 个按钮,1 个代表“毫米”,1 个代表“英寸”。当按下这些按钮时,需要首先将事件类别从默认值(毫米)更改为英寸(正在运行)。
它还必须将字段图标从“毫米”更新为“英寸”(正在运行)。
我正在努力使用我的过滤器,我需要它在单击时工作 - 我的 Controller 中已经有一个函数可以单击运行并通过更新 $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
}
我希望它在我的 Controller 中的单击功能中运行,并将 View 上的任何尺寸转换为英寸,然后当单击 mm 时转换回原来的方式。
任何帮助启动和运行的帮助都将不胜感激。
最佳答案
将 activeUnit
作为参数传递给模板中的过滤器应该可以正常工作吗?你尝试过吗?更改 activeUnit 应该通过绑定(bind)自动更新值。
<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
除非您决定该值始终以毫米
或英寸
为单位,否则它可能是错误且令人困惑的数据。
如果你能描述你最初的需求,事情可能会更清楚。
- 您是否只是显示一个固定值,用户可以通过切换单位来查看?
- 您是否有一些输入字段,用户可以在其中输入任何单位的值?
关于javascript - 在 AngularJS 中使用过滤器 onclick 进行毫米 - 英寸转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289584/