0

I'm trying to put together a CRUD setup for a domain entity that includes a file. On the front end I have an input of type=file, like so:

<input type="file" name="file" ng-model="template.file" required />

As you can see this is bound to my model.

The creation part works well, because it's necessary to add a file at that point, so the file input required validation is satisfied. When editing however, the user may never change the file but because it's a file input and I've not found a way to re-populate it, the required file input field never passes validation.

One way I've thought of is to force the file input field to be valid on load, hence the question title (not sure exactly how to do that) but I realize this may not fit with the principals of Angular.

Is there a reliable way, preferably the "angular way" to do this?

A. Murray
  • 2,761
  • 5
  • 27
  • 40

2 Answers2

1

You can use ng-required directive

 <input type="file" name="file" ng-model="template.file" ng-required="!template.file" />

Another answer from here

Community
  • 1
  • 1
allenhwkim
  • 27,270
  • 18
  • 89
  • 122
  • Thanks @allenhwkim, this seems like the simplest solution. I've basically set up a flag called addMode which is defined as true in the create screen and is undefined in the edit screen and ng-required="addMode" does the exact validation I'm looking for. – A. Murray Jan 13 '14 at 09:03
0

You can set it valid by adding your form a name. Then you just could do in controller:

    $scope.myform.file.setValidity(true);
makallio85
  • 1,366
  • 2
  • 14
  • 29
  • I guess this is best you can do with files. Better way, of course, would be wrapping this all in directive. – makallio85 Jan 10 '14 at 16:00
  • Thanks @AngularAddict, this works when I simply resubmit the form, changing nothing, but if I empty one of the other fields and sumbit the file input is also flagged. Angular must recheck the rest of the model if a required validation rule is broken. I'm going to put together a plunkr and post it here. – A. Murray Jan 10 '14 at 16:18