Pass obj from directive to controller in AngularJS

68 просмотра

1 ответ

157 Репутация автора

I'm trying to write a directive that get the parent controller and parent form controller and pass them as a single object to my controller, this is what I have:


<div ng-controller="ParentController as self" ng-form="ParentForm">

  <div ng-controller="ChildController1 as self" my-parent="self.parent">
    ChildController1 parent:<br/>


  <div ng-controller="ChildController2 as self" my-parent="self.parent">
    ChildController2 parent:<br/>



myApp.directive('myParent', function() {
  var directive = {
    restrict: 'A',
    link: link

  return directive;

  function link(scope, element, attrs) {
    var parentElement = element.parent();
    var parentCtrl = parentElement.controller();
    var formCtrl = parentElement.controller('form');

    var parent = parentCtrl;
    parent.form = formCtrl;

    console.log("directive parent obj: ", parent);

    // How can I pass the parent obj to controller???

I've wrote a plunker here to better explain the situation:

I know that in this case I could use controllerAs with different names in my controllers, but I need to make it work with a directive ("restrict: A" directive).

Can someone please help me with this problem?

Автор: bymere Источник Размещён: 07.09.2016 09:36

Ответы (1)

1 плюс

8489 Репутация автора

If You not declare own scope for directive then directive scope is the same as controller scope, so controller and directive can access the same scope data. If You need to do something in controller launched from directive then in controller watch scope variable using $

If You need pass variable from one component to another ( controller to directive or vice versa ) use services. Example service with getter and setter:







Add service in controller and use setData, and add it to directive and call getData.

Example controller code:


Example directive

var form=myService.getData();
Автор: Maciej Sikora Размещён: 07.09.2016 09:45
Вопросы из категории :