I've created a simple "modal dialog" directive, which uses transclude. I would like to place a form () inside the "modal dialog" directive. I would expect that formController of a form placed inside the directive, is going to be accessible in parent controller's scope, however it isn't. Take a look at the following fiddle, please: http://jsfiddle.net/milmly/f2WMT/1/
Complete code:
<!DOCTYPE html>
<html>
<head>
<title>AngJS test</title>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/foundation/4.0.9/css/foundation.min.css">
<style>
.reveal-modal {
display: block;
visibility: visible;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('appCtrl', function ($scope) {
$scope.model = {
id: 1, name: 'John'
};
$scope.modal = {
show: false
};
});
app.directive('modal', function () {
return {
scope: {
show: '='
},
transclude: true,
replace: true,
template: '<div class="reveal-modal small" ng-show="show"><div class="panel" ng-transclude></div></div>'
}
});
</script>
</head>
<body ng-app="app">
<div ng-controller="appCtrl">
<div class="panel">
Id: {{ model.id }}<br>
Name: {{ model.name }}<br>
Controller formController: {{ form }}<br>
Directive formController: {{ myForm }}<br>
</div>
<form name="form" class="panel">
<input type="text" ng-model="model.name">
</form>
<a ng-click="modal.show=!modal.show">toggle dialog</a>
<div modal show="modal.show">
<form name="myForm">
<input type="text" ng-model="model.name">
</form>
</div>
</div>
</body>
</html>
So my question is how to access or is it possible to access directive's formController from parent controller?
Thank you for answers.
-Milan
Because you are using transclude, the directive will create a child transcluded scope. There is no easy path from the controller scope (003) to the directive's transcluded scope (005):
(The hard/not recommended path is to go via private property $$childHead
on the controller scope, find the isolate scope, then use $$nextSibling
to get to the transcluded scope.)
Update:
From insights from this answer, I think we can get the formController inside the directive, then use =
to get it to the parent.
scope: { show: '=', formCtrl: '=' },
...
link: function(scope, element) {
var input1 = element.find('input').eq(0);
scope.formCtrl = input1.controller('form');
}
HTML:
<div modal show="modal.show" form-ctrl="formCtrl">
Fiddle
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