I am using an Angular 1.5 Material Design $mdDialog
in the recommended way, using controllerAs: "dialog"
. In the template I have a form: <form name="fooForm"
. Within the template I can access the form with no problem, e.g. ng-disabled="fooForm.$invalid || fooForm.$submitted"
.
But how do I access that form from within the $mdDialog
controller? From what I read, I would expect to be able to do this:
const doFoo = () => {
if (this.fooForm.$dirty) {
Here this
is the dialog controller.
But I get an error: TypeError: Cannot read property '$dirty' of undefined
. And sure enough, if I put a breakpoint in the code, the controller has no fooForm
property.
I've tried using $scope
as well, but when I put a breakpoint in the code $scope
has no fooForm
property either.
Here's my dialog template:
<md-dialog aria-label="FooBar">
<md-toolbar>
<div class="md-toolbar-tools">
<h2>FooBar</h2>
<span flex></span>
<md-button class="md-icon-button" ng-click="dialog.cancel()">
<md-icon>close</md-icon>
</md-button>
</div>
</md-toolbar>
<form name="fooForm" ng-submit="dialog.ok()" novalidate>
<md-dialog-content>
<div layout="column" layout-padding>
<h2 class="md-headline">Foo</h2>
<div layout="row" layout-xs="column">
...
</div>
</md-dialog-content>
<md-dialog-actions>
<md-button class="md-primary" type="submit" ng-disabled="fooForm.$invalid || fooForm.$submitted">
OK
</md-button>
<md-button ng-click="dialog.cancel()">
Cancel
</md-button>
</md-dialog-actions>
</form>
</md-dialog>
How do I access a form in an $mdDialog
from the dialog controller?
you need to assign the form to the Scope of the Controller. Do this by changing the form name from fooForm
to dialog.fooForm
.
<form name="dialog.fooForm" ng-submit="dialog.ok()" novalidate>
function controller($scope) { var vm = this; vm.click = function() {} $scope.click = function() {} } <button ng-click="xxx.click()" ... <button ng-click="click()" ...
Now if you write ng-click="whatever();smth();"
angular will use $parse(expression)(scope)
to parse this expression.
Now you write form name="formName"
-- angular will use $parse("formName").assign(scope, form);
and put it to scope.
$parse is quite clever and can easily handle nested properties, to put form to your controller (as xxx): <form name="xxx.myForm"></form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With