The other answers may work but it seems they are overcomplicating things. If you use "controller as", you can just give the form a name based on the alias and be done with it.
Take a look at the following example. I just name the form as a property on my controller, and then as you can see from the JavaScript I can reference it directly by name. No tricks, gimmicks, or strange work arounds and no need to rely on $scope
.
(function (app) {
function ctrl() {
}
angular.extend(ctrl.prototype, {
email: '',
submit: function () {
if (this.ctrlForm.email.$invalid) {
alert("Invalid email!");
return;
}
alert("Submitted " + this.email);
this.email = '';
this.ctrlForm.$setPristine();
}
});
app.controller("formCtrl", ctrl);
})(angular.module("formExample",[]));
<script src="https://code.angularjs.org/1.3.9/angular.min.js"></script>
<div ng-app="formExample" ng-controller="formCtrl as ctrl">
<form name="ctrl.ctrlForm" role="form" novalidate="">
<input name="email" type="email" required="" ng-model="ctrl.email" placeholder="Enter a valid email."/>
<div ng-if="ctrl.ctrlForm.email.$invalid">Email is invalid!</div>
<button ng-click="ctrl.submit()" ng-disabled="ctrl.ctrlForm.$invalid || ctrl.ctrlForm.$pristine">Submit</button>
</form>
</div>
Note that formCtrl
is the name I register the controller with, and ctrl
is the alias for my controller (some people might prefer vm
, so I name the form ctrl.ctrlForm
. That is how I reference it in the HTML. The controller then gets that property, so it is referenced simply as this.ctrlForm
.
Also as a fiddle: http://jsfiddle.net/jeremylikness/du5ptxyc/