AngularJS: Access formController of a form placed inside transcluded directive from parent controller

五迷三道 提交于 2019-12-02 17:36:15
Mark Rajcok

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

Here is my solution: I create such method in parent controller :

$scope.saveForm = function(form) {
  $scope.myForm = form;
};

Then I call it in transcluded content:

<my-directive>
  <form name="myForm">
     <div ng-init="saveForm(myForm)"></div>
  </form>
</my-directive>

After creating directive instance i have form controller instance in parent scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!