How to refer to named forms with “controller as” syntax
I’m having trouble referring to named forms in my controller when using the “controller as” syntax in angularjs. For example, given the following HTML:
<div ng-controller="MyController as ctl">
<form role="form" name="newItemForm">
<input type="text" id="firstName" ng-model="ctl.firstName"/>
</form>
</div>
In the context of the controller,
function MyController() {
var self = this;
console.log(self.newItemForm);
}
self.newItemForm
is undefined. If I had been using the $scope convention, I could have referred to $scope.newItemForm. Is there any other way of doing this in the controller as syntax without using the scope?
Change your HTML to this:
<div ng-controller="MyController as ctl">
<form role="form" name="ctl.newItemForm">
<input type="text" id="firstName" ng-model="ctl.firstName"/>
</form>
</div>
Then you will be able to access the named form as expected in your controller without injecting $scope
. Found this information here: http://www.technofattie.com/2014/07/01/using-angular-forms-with-controller-as-syntax.html
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .