Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to named forms with "controller as" syntax

Tags:

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?

like image 342
cayblood Avatar asked Mar 20 '14 16:03

cayblood


Video Answer


1 Answers

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

like image 82
quentin-starin Avatar answered Oct 28 '22 00:10

quentin-starin