Accessing angular bootstrap modal form from controller

Accessing angular bootstrap modal form from controller

I am trying to access the form from the modal controller (Plunkr) but myForm doesn’t seem to be accessible. How to get alert call to work:
angular.module(‘plunker’, [‘ui.bootstrap’]);
var ModalDemoCtrl = function ($scope, $modal, $log) {
$ = function () {
var modalInstance = ${
templateUrl: ‘myModalContent.html’,
controller: ModalInstanceCtrl

var ModalInstanceCtrl = function ($scope, $modalInstance) {
$scope.submit = function() {
// How to get this?

$scope.ok = function () {

$scope.cancel = function () {

And template:

Selection from a modal: {{ selected }}


Solution 1:

This was an known bug in ui-bootstrap. So injecting $modalInstance works fine now.

Workaround is to pass form instance to the submit function explicitly:

<form name="myForm" novalidate ng-submit="submit(myForm)">
  <div class="modal-header">
    <h3>I'm a modal!</h3>
  <div class="modal-body">
    <input type="email" value="hello">
  <div class="modal-footer">
    <button class="btn btn-primary" type="submit">OK</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
var ModalInstanceCtrl = function ($scope, $modalInstance) {
  $scope.submit = function(myForm) {

Solution 2:

Angular-UI modals are using transclusion to attach modal content, which means any new scope entries made within modal are created in child scope. This happens with form directive.

You can try to attach form to parent scope with (Angular 1.2.16):

<form name="$parent.userForm">

The userForm is created and available in modal’s controller $scope. Thanks to scope inheritance userForm access stays untouched in the markup.

<div ng-class="{'has-error':$invalid}"}>

Solution 3:

In your controller add at the top:

$scope.form = {};

In the html template:

<form name="form.yourFormName">

Validation on html elements:

<div ng-class="{'has-error':$invalid}"}>

See also:

AngularJS modal dialog form object is undefined in controller

Solution 4:

In the end I went with the answer given by gertas, but the following is another way of resolving this.

//place a method on modal controller scope

        $scope.setFormReference = function (myForm) {
            $scope.myForm = myForm

//call this using an angular expression in your modal template

       {{ setFormReference(loginForm)}}


Related:  Twitter Bootstrap Responsive - Show Table Column only on Desktop