gpt4 book ai didi

angularjs - 如何在angularjs表达式中将字符串转换为数字或日期

转载 作者:行者123 更新时间:2023-12-04 14:58:12 24 4
gpt4 key购买 nike

我正在使用 angularjs 来制作分页类型的东西,比如说我有一个 2D 数组,我正在显示它的值。它工作正常,但我也希望能够编辑这些值,所以我在输入标签中使用了 ng-hide,它工作正常,但问题是,如果输入的类型是数字或日期,我的数组值的类型是字符串那么这些值不会显示在可编辑的输入框中。

代码:

<table class="table table-hover">
<thead>
<tr class="active">
<th class="id">Label</th>
<th class="name">Field</th>
</tr>
</thead>

<tbody>
<tr ng-repeat="item in fieldsonPage[currentPage]" class="active">
<td>{{item}}</td>
<td>
<div ng-repeat="prop in pagedItems[currentPage]" class="active">
<div ng-hide="ngEditName" ng-click="ngEditName=!ngEditName">
{{prop[item]}}
</div>
<div ng-show="ngEditName">
<input type="{{fieldsType[item]}}" ng-hide="{{fieldsType[item] == 'textarea' ? 'true' : 'false'}}" ng-model="prop[item]" class="form-control"/>
<textarea rows="4" cols="50" ng-hide="{{fieldsType[item] == 'textarea' ? 'false' : 'true'}}" class="form-control" ng-model="prop[item]" /><div ng-click="ngEditName=!ngEditName">Close</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>

类型取决于正在工作的相关数据类型,但绑定(bind)不正确,因此我需要一种方法 将字符串转换为html页面表达式中的数字或日期本身。任何线索!
enter image description here

最佳答案

这种方式使用指令自动将数字转换为字符串,反之亦然。我的意思是使用 input元素 type=number绑定(bind)到 string多变的。

这是通过使用 $formatters 和 $parsers 来完成的。

app.directive('numberConverter', function() {
return {
priority: 1,
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
function toModel(value) {
return "" + value; // convert to string
}

function toView(value) {
return parseInt(value); // convert to number
}

ngModel.$formatters.push(toView);
ngModel.$parsers.push(toModel);
}
};
});

HTML
 <input type="number" number-converter ng-model="model.number">

更多信息:

ngModel.$formatters

Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation.



ngModel.$parsers

Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.



PLUNKER

源文档: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

关于angularjs - 如何在angularjs表达式中将字符串转换为数字或日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25657130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com