I have an AngularJS form that contains - among other fields - one of type url
. The latter is important as this forces the corresponding input to be a valid URL.
Under certain conditions (for instance, a modal dialog with such a form is to be closed), I want to clear that form programmatically. For that purpose, I implemented method reset
that basically clears the corresponding form model by setting $scope.formData = {}
. Thus, it sets the form model to a new, blank object.
While that assignment clears all valid fields in the rendered HTML form, it does not clear invalid fields, like an invalid URL. For instance, if the user would provide invalid input ht://t/p
as URL, that input would not be removed from the rendered form.
I think this is due to the fact that any invalid URL is not reflected by the model - such an invalid URL just wouldn't "make" it to the model because it does not pass validation in the NgModelController#$parsers
array. Thus, in the model - there is no URL at all. Consequently, resetting the form model to {}
cannot actually change the model's URL as it has not been set yet.
However, if method reset
explicitly sets field $scope.formData.url = ""
, the invalid URL will be cleared properly (at least, the rendered form won't show it anymore). This is caused by the explicit change of the URL in the model. However, now, model variable formData.url
contains the empty string (well, not surprisingly), while by using = {}
, all fields would be undefined
instead.
While assigning individual fields to ""
works as workaround for simple forms, it quickly becomes cumbersome for more complex forms with many fields.
Thus, how could I programmatically reset the form efficiently and effectively - including all invalid input fields as well?
I created a Plunker at http://plnkr.co/c2Yhzs where you can examine and run a complete example showing the above effect.
$scope.formData = {}
– Maxim Shoustin Dec 9 '13 at 19:16$scope.formData = {}
, only the model is reset. – Martin Dec 10 '13 at 9:36