I have a form where the contents are loaded by ng-include
:
<form ng-submit="submitForm()">
<div ng-include="currentForm"></div>
</form>
The ng-include
d fields will not have any ng-model
s associated with them, for example:
<input type="number" name="age" />
<input type="submit" value="Submit" />
How can I access the form data from within the submitForm
function?
$scope.submitForm = function() {
// access form variables here
}
I've tried examining this
within submitForm
but that just spits out the ChildScope
object.
You can do this the easy ugly way, or you could do this the elegant pompous way:
The easy way is to pass the $event
object to the submit form, and extract the form fields from there:
<form ng-submit="submitForm($event)">
<input name="bar">
</form>
And handle this in the controller:
$scope.submitForm = function(event){
var bar = event.currentTarget.bar.value;
}
The more elegant way is to define a directive that adds ng-model
to input elements in the included form and re-compiles it. Suppose it is used like below, and it publishes the form ng-models onto fooModel
on the scope:
<div ng-include="'form.html'" included-form-model="fooModel"></div>
Theoretically, it could look like so (the example assumes full jQuery is included, for simplicity of illustration, and all form elements have name
attribute defined):
.directive("includedFormModel", function($compile){
return {
require: "?ngInclude",
link: function(scope, element, attrs, ngInclude){
if (!ngInclude) return;
var model = attrs.includedFormModel; // the name under which to publish
scope.$parent[model] = {};
var unwatch = scope.$on("$includeContentLoaded", function(){
inputElements = element.find(":input").each(function(idx, elem){
elem.setAttribute("ng-model", model + "." + elem.name);
});
$compile(inputElements)(scope);
});
scope.$on("$destroy", function(){ unwatch(); });
}
}
});
最好在元素上使用ng-model。但是您可以通过jquery访问它
$( "input[name='age']")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.