I'd like a custom control that uses ngModel.$formatters
to be able to format data as soon as a server dependency loads in. In my case, it needs to load a lookup table to go from one kind of id to another. $modelValue
stores one thing $viewValue
displays another. Pretty straight-forward stuff.
The trick is that if my lookup table isn't loaded, I can't do the formatting into a $viewValue.
Once my data loads, I need to do the following:
ngModel.$formatters.push(myFormatter)
$modelValue -> $formatters -> $viewValue
$render()
doesn't work, this just moves the value from $viewValue
into the UI control.
$rollbackViewValue()
looks promising, but that's only in an unstable version (1.3.0-beta.18).
Code Sample:
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.
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With