Problem with custom directive using ng-model and ng-model-options.

117 views
Skip to first unread message

Paul Selden

unread,
Oct 6, 2015, 4:56:53 PM10/6/15
to AngularJS
I'm trying to create a custom "range" directive that uses ng-model and only triggers model updates on blur.

To accomplish this, I combined two input[type=number] directives that use ng-model to take a min and a max value and format/parse a model that looks like "1 - 10". Then when I actually use the input I add ng-model-options={ updateOn: 'blur'} to so it should only trigger the update on blur.

The problem is that my model is never being updated, even on blur. It looks like the ng-change event gets triggered by the input on blur, but the $setViewValue of the custom directive doesn't send it through the parsers pipeline.

Here is a plunkr that demonstrates it: http://plnkr.co/edit/ZMReb5pAi1CBcZRDHJqv?p=preview

What exactly is going on here? The only "solution" i can figure out is to force a $commitViewValue in my onValueChange function, but that makes it so it commits it as soon as i blur any of the individual inputs, not the entire thing. Any ideas?

Sander Elias

unread,
Oct 6, 2015, 11:39:07 PM10/6/15
to AngularJS
Hi Paul,

Problem is, you have created an synthesized element. That element never retrieves a blur event. The reason for this, is that a blur event does not bubble up. When you move the focus away from either one of your inputs, those will fire a blur event. And keep that blur for themselves sort of speak.
This can be solved by manually fire a blur event when either of your blur events fire, and the focus isn't on the other one.

Regards
Sander 

Paul Selden

unread,
Oct 7, 2015, 10:39:32 AM10/7/15
to AngularJS
Thanks Sander!


My only concern now is that the inner input validations still fire even when you click on the other input, but I don't suppose I could do too much about that without manually doing the validation checks and calling setValidity.

-Paul

Sander Elias

unread,
Oct 8, 2015, 12:13:32 AM10/8/15
to AngularJS
Hi Paul,

If you check the validity on blur, and you stay withing your own element, put the focus back on the offending part. (while informing the user of coarse).
The net effect will be that if the user stay's in the invalid input, while inside the control. If the user indeed blurs out of the control, you indeed need to set the validity of your outer control. (and possible set the inner form to $pristine)

Regards
Sander
Reply all
Reply to author
Forward
0 new messages