Reputation: 4504
All,
I have a form inside an Angular controller. But the name of that form is dynamically-generated (by Django) from the server. Does anybody know how I can access that form (w/ the intention of changing the validity of certain items after some interaction w/ the server).
Here is some code:
my_template.html:
<html>
<div ng-app="MyApp">
<div ng-controller="MyController as my_controller">
<form name={{ form.form_name }}
{% for field in form %}
{{ field }}
{% endfor %}
</form>
<button ng-click="do_something">do something</button>
</div>
</div>
</html>
my_view.py:
def my_view(request):
form = MyForm(form_name=generate_a_random_string())
return render_to_template({"form":form}
return render_to_response('my_template.html', {"form": form})
my_app.js:
(function() {
var app = angular.module("MyApp");
app.controller("MyController", ['$scope', function($scope) {
$scope.do_something = function() {
/* OBVIOUSLY THIS DOESN'T WORK */
/* BUT WHAT DO I REPLACE "my_form" WITH ? */
my_form['some_field_name'].$setValidity('some_validity_type', false);
my_form['some_field_name'].$setDirty();
}
}]);
});
If it helps, I am using django-angular to make my Django forms play nicely w/ Angular.
Thanks.
Upvotes: 0
Views: 420
Reputation: 6813
The name of the form as in
<form name="myForm">
will be reflected in your controller as a NgFormController of the same name
myController.myForm
I think part of the problem is that you have {{ form.form_name }}
in your template which from what I can tell hasn't been initialized in your controller.
You probably need to initialize your form names inside your controller first, then use an ng-repeat to build your form DOM elements and pull the name from there. Then you can access the NgFormController by using this.form_name
inside your view controller.
Upvotes: 0