Trigger ng-model.$formatters to run programmatically

荒凉一梦 提交于 2019-12-04 03:42:55
Joe Enzminger

Looking at the code for ngModelController, it appears that what you stumbled upon (setting $modelValue to anything other than the current actual model value) is the accepted way to do this. As you say, the value you set is not used: it just triggers the update. Check its current value first to make sure it actually changes (or use a very unlikely value).

if (ngModel.$modelValue == 'bar')
    ngModel.$modelValue = 'foo';
else
    ngModel.$modelValue = 'bar';

Here is a related question.

Also, there is an active pull request that looks like an "official" way of doing this is forthcoming.

The reason it works is that ngModelController sets up a $watch that runs every digest cycle that compares $modelValue to the value that ng-model is bound to. If they don't match, it triggers the $formatters pipeline.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!