Jinto
Jinto

Reputation: 865

Angularjs directive require is not finding the parent directive controller

When I require a controller in a directive, I am getting error saying that, not able to find the controller. Please see the code with the issue below. http://plnkr.co/edit/NzmQPA?p=preview

Can someone please have a look at it?

Thanks

Upvotes: 0

Views: 1036

Answers (2)

Khanh TO
Khanh TO

Reputation: 48972

You should use require when your directives are related: like an accordion and accordion items.

To communicate between scopes, you should try $on, $emit, $broadcast. In your case, you need to inject rootScope into your directive, and broadcast an event from rootScope:

.directive('searchResultHeader', 

    function($rootScope) { //inject rootScope
      return {
        replace: true,
        template: '<button>clickme</button>',
        link: function($scope, $elem, $attrs) {
          $elem.on('click', function() {
            $rootScope.$broadcast("someEvent"); //broadcast an event to all child scopes.
          });
        }
      };
    }
  );

Any scopes interested in the event can subscribe to it using $on:

function($scope) {
      $scope.$on("someEvent", function() { 
          alert('this is working');
      });
    }

Using events is a way to create decoupled systems.

DEMO

Upvotes: 1

Craig Squire
Craig Squire

Reputation: 2141

You should use a service to communicate between them. Exactly how/what you do depends on your exact needs (there's not enough info in your post).

Side note, I changed your click handler to an ng-click.

Here's an example: http://plnkr.co/edit/I2TvvV?p=preview

<div search-result-filter></div>
<div search-result-header ng-click="doClick()"></div>

angular.module('mymodule', [])
  .controller('mainCtrl', ['$scope',
    function($scope) {
      $scope.test = "main angular is working";
    }
  ]).controller('searchResultFilterController', ['$scope', 'myService',
    function($scope, myService) {
      //do something with 'myService'
    }
  ])
  .directive('searchResultFilter', [
    function() {
      return {
        replace: true,
        controller: 'searchResultFilterController',
        template: '<h1>this is the first directive</h1>'
      };
    }
  ])
  .directive('searchResultHeader', ['myService',
    function(myService) {
      return {
        replace: true,
        template: '<button>clickme</button>',
        link: function($scope, $elem, $attrs) {
          $scope.doClick = function() {
            myService.someFn();
          };
        }
      };
    }
  ])
  .service('myService', function() {
      this.someFn = function() {
        alert('this is working');
      };
  });

Upvotes: 1

Related Questions