ngModel 格式化程序和解析器 [英] ngModel Formatters and Parsers
问题描述
我以不同的形式发布了相同的问题,但没有人回答.我没有清楚地了解格式化程序和解析器在 angular js 中的作用.
I posted the same question in different form, but no one answered. I am not getting a clear picture of what the Formatters and Parsers do in angular js.
根据定义,格式化程序和解析器看起来都与我相似.也许我错了,因为我是这个 angularjs 的新手.
By the definition, both the Formatters and Parsers look similar to me. Maybe I am wrong, as I am new to this angularjs.
每当模型值发生变化时,作为管道执行的函数数组.依次调用每个函数,将值传递给下一个.用于格式化/转换值以在控件和验证中显示.
每当控件从 DOM 读取值时,作为管道执行的函数数组.依次调用每个函数,将值传递给下一个.用于清理/转换值以及验证.对于验证,解析器应使用 $setValidity() 更新有效性状态,并为无效值返回 undefined.
请用一个简单的例子帮助我理解这两个功能.对两者的简单说明将不胜感激.
Please help me to understand both features with a simple example. A simple illustration of both will be appreciated.
推荐答案
这个主题在一个相关问题中得到了很好的介绍:如何在AngularJS中做双向过滤?
This topic was covered really well in a related question: How to do two-way filtering in AngularJS?
总结:
- 格式化程序更改模型值在视图中的显示方式.
- 解析器改变了视图值在模型中的保存方式.
这是一个简单的例子,建立在 NgModelController api 文档中的一个例子的基础上:
Here is a simple example, building on an example in the NgModelController api documentation:
//format text going to user (model to view)
ngModel.$formatters.push(function(value) {
return value.toUpperCase();
});
//format text from the user (view to model)
ngModel.$parsers.push(function(value) {
return value.toLowerCase();
});
您可以看到它的实际效果:http://plnkr.co/UQ5q5FxyBzIeEjRYYVGX?plnkr=legacy一个>
You can see it in action: http://plnkr.co/UQ5q5FxyBzIeEjRYYVGX?plnkr=legacy
<input type="button" value="set to 'misko'" ng-click="data.name='misko'"/>
<input type="button" value="set to 'MISKO'" ng-click="data.name='MISKO'"/>
<input changecase ng-model="data.name" />
当您在(查看模型)中键入名称时,您将看到模型始终为小写.但是,当您单击按钮并以编程方式更改名称(要查看的模型)时,输入字段始终为大写.
When you type a name in (view to model), you will see that the model is always lowercase. But, when you click a button and programatically change the name (model to view), the input field is always uppercase.
这篇关于ngModel 格式化程序和解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!