Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger ng-model.$formatters to run programmatically

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)
  • Tell ngModel to start the pipeline from $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.
});
like image 242
SimplGy Avatar asked Aug 21 '14 22:08

SimplGy


1 Answers

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.

like image 165
Joe Enzminger Avatar answered Oct 05 '22 02:10

Joe Enzminger