【发布时间】:2014-10-15 16:45:32
【问题描述】:
我想要一个使用 ngModel.$formatters 的自定义控件,以便能够在服务器依赖项加载后立即格式化数据。在我的情况下,它需要加载查找表以从一种 id 转到另一种. $modelValue 存储一件事 $viewValue 显示另一件事。非常直接的东西。
诀窍是,如果我的查找表没有加载,我无法将格式设置为 $viewValue。
加载数据后,我需要执行以下操作:
ngModel.$formatters.push(myFormatter)- 告诉 ngModel 从
$modelValue -> $formatters -> $viewValue开始管道
$render() 不起作用,这只是将值从$viewValue 移动到 UI 控件中。
$rollbackViewValue() 看起来很有希望,但这只是不稳定的版本 (1.3.0-beta.18)。
代码示例:
mappingTable.load().then(function(data){
mappingData = data;
ngModel.$formatters.push(myFormatter); // needs mappingData in order to function
// TODO: Tell ngModel to run the existing $modelValue through $formatters to calculate a new $viewValue and $render it
//ngModel.$render() // doesn't work, only puts the $viewValue in the DOM element.
});
【问题讨论】:
-
奇怪的是,我可以在数据加载后设置
ngModel.$modelValue = 'foo'(字面意思是 foo)。这会导致管道运行,但与之前的模型值相反。最后,modelValue是我想要的,viewValue是我想要的解析后的版本,'foo'无处可寻。完美运行,但我不相信/不理解它。 -
尝试调用
$scope.$apply(),这将触发新的$digest循环,该循环应该使用更新的$formatters
标签: javascript angularjs angular-ngmodel