Josh Diehl
Josh Diehl

Reputation: 3079

How do I pass a form explicity as a function parameter

Angular 1.3.0. I am trying to use the $setPristine method on a form, trouble is I have multiple similar forms on the same page, each with a dynamic name. Every example of $setPristine I have been able to find uses this syntax: $scope.myFormName.$setPristine(). I could try to do a dynamic eval by passing the variable part of the dynamic form name to the function, so that it could use the myFormName syntax. BUT it seems like it would be cleaner to pass the form to the function explicitly, not to mention more testable than using $scope.

What I want:

HTML

... loop over things
<form name="thing_form_{{thing.id}}">
... inputs and stuff
    <input type="submit" ng-click="thing = reloadThing(thing, thisform); " value="Do">
</form>

Coffeescript

$scope.reloadThing = (thing, form) ->
        ... do stuff
        form.$setPristine()

Upvotes: 0

Views: 1742

Answers (1)

Joe
Joe

Reputation: 2596

You can pass the form name as a string and use that to set the form as pristine...

HTML

... loop over things
<form name="thing_form_{{thing.id}}">
    ... inputs and stuff
    <input type="submit" ng-click="thing = reloadThing(thing, 'thing_form_' + thing.id ); " value="Do">
</form>

Coffeescript

$scope.reloadThing = (thing, formName) ->
        ... do stuff
        $scope[formName].$setPristine()

Update:

If you absolutely need to pass the form object into the function instead of evaluating it on the scope, you can use this in your ngrepeat to access the $scope from the template. So you would end up with something like this:

HTML

... loop over things
<form name="thing_form_{{thing.id}}">
    ... inputs and stuff
    <input type="submit" ng-click="thing = reloadThing(thing, this['thing_form_' + thing.id] ); " value="Do">
</form>

Coffeescript

$scope.reloadThing = (thing, form) ->
        ... do stuff
        form.$setPristine()

Upvotes: 2

Related Questions