angularjs - 更改 View 值而不更改模型值

标签 angularjs angularjs-directive

我将小时字段以分钟为单位存储在数据库中,因此我需要更改该值以以小时为单位显示。

我还没有代码。

我想到了一些替代方案,我想知道是否有人尝试过:

我会将指令作为属性并将值作为指令的属性传递,对值执行我需要的操作,然后将最终值(例如 15:59)放入元素。

我也会制作一个指令,但是这个指令将是一个 self 控制的元素,当用户输入一个值时,我将转换为分钟,但在 View 中将保留用户输入的值。

更好的方法是什么?

最佳答案

这取决于您是否需要用户输入。如果您这样做,则必须使用 2 路指令,如下所示。

在 Angular 指令链接函数中,您有 4 个参数:

function (scope, element, attrs, controller)

Controller 参数允许您操纵指令的 ng-model。最重要的是 Controller 有一个叫做 $formatters 和 $parsers 的东西。这些 $formatters 和 $parsers 允许您准确地执行您想要执行的操作,因为它将允许您将模型和 View 值作为指令的一部分进行操作。

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$parsers

格式化程序将允许您设置模型在 View 中的查看方式(初始加载) 解析器将允许您设置如何将 View 保存到模型(用户输入)

这可以按如下方式完成:

directive code
....
link: function (scope, element, attrs, controller) {
   function hoursToMinutes(viewValue){
     viewValue = ...Conversion logic...
     controller.$viewValue = viewValue;
     return viewValue;
   }
   function minutesToHours(modelValue){
     modelValue= ...Conversion logic...
     controller.$modelValue= modelValue;
     return modelValue;
   }
   controller.$parsers.push(hoursToMinutes);
   controller.$formatters.push(minutesToHours);
}
....

关于angularjs - 更改 View 值而不更改模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31295021/

相关文章:

javascript - 无法通过 AngularJs 加载 Google map

javascript - angularjs 服务不是函数

angularjs - 如何为自定义指令实现 ng-change

angularjs - Angular js 数据绑定(bind)不会间歇性更新 View

angularjs - 背景图像错误时的 Angular 回落图像

json - 尝试显示 json 数据时,Materialize 折叠无法正常工作

javascript - 如何使用 angularjs 更新 visjs 的节点或边缘属性?

javascript - 最佳实践 : Wrap a template in another template in AngularJS?

javascript - Angular 的动态属性

AngularJS : How to pass data from directive to controllers function