我正在使用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>
类型取决于正在工作的关联数据的类型,但是绑定不合适,因此我需要一种将字符串转换为html页面本身表达式中的数字或日期的方法。任何线索!
This way uses a directive to automagically converts numbers to string and viceversa. I mean using an input
element type=number
binded to a string
variable.
This is done by using, $formatters and $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
每当控件从DOM读取值时,作为管道执行的函数数组。依次调用每个函数,将值传递给下一个。最后的返回值用于填充模型。用于清除/转换值以及进行验证。为了进行验证,解析器应使用$ setValidity()更新有效性状态,并为无效值返回undefined。
源文档:https : //docs.angularjs.org/api/ng/type/ngModel.NgModelController
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句