简体   繁体   中英

Inject Directive's Controller inside the same Directive

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 (ie Changing routes). When I go from route A to route BI 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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM