0

I'm building an application based on AngularJs and GMaps API v3. The issue I've came up with is that I need a way to call methods of the directive's controller from another directives (that's easy with require) and from the same directive.

Let's put it in an example:

I've got a directive that renders the map using GMaps JS lib. and also render some markers and also I've got another directive that handles navigation (i.e. Changing routes). When I go from route A to route B I need to erase the markers and leave the map blank.

So which is the best way to achive this? Should I build three directives? One with all the render methods and destroy markers methods and then call them from the other directives? Or is there a way to inject the directive's controller into the same directive?

Facu Ferrari
  • 145
  • 1
  • 2
  • 17

2 Answers2

1

So I've googled a bit an I've found this!

https://github.com/bennadel/AngularJS-Directive-Controllers/blob/master/app/directives/master.js#L11

Just like you said @musically_ut the controller is executed before the link function so it's could be injected into the link func. and make it's method available.

Facu Ferrari
  • 145
  • 1
  • 2
  • 17
0

The controller for a directive executes before the link function and all $scope declarations made in the controller are available on the scope of the same directive.

Hence, the controller is injected into the directive itself.

Demo: http://plnkr.co/edit/HnwJ0w0VTLbNOC87k74n?p=preview

musically_ut
  • 34,028
  • 8
  • 94
  • 106
  • mmmm, I've tried something like this: controller: function() { this.method = function() { do something } }, link: function(Controller){ Controller.method(); } And didn't worked :( – Facu Ferrari Nov 24 '13 at 23:55
  • @FacuFerrari Check the attached demo. – musically_ut Nov 24 '13 at 23:59
  • mmm I think that if I attach it to the $scope it would be the same that declaring the method in a global Controller. Isn't it? – Facu Ferrari Nov 25 '13 at 00:01
  • @FacuFerrari I think you are confusing `$rootScope` with `$scope`. Also, have a look at this: http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers – musically_ut Nov 25 '13 at 00:01
  • Yeah, maybe, please take a look at this. That is what I want to achieve: http://plnkr.co/edit/pArUFDIWwZmxDXxCW3cG?p=preview – Facu Ferrari Nov 25 '13 at 00:10
  • @FacuFerrari This seems to work: http://plnkr.co/edit/fLcCIHe4Y4WvOsNYxVPW?p=preview Note that you need to nest the directives to share the controllers. Otherwise, I would recommend having separate controllers and using a common service to share the information between them. – musically_ut Nov 25 '13 at 06:25