Zoom in link function in AngularJS

Typically, in all AngularJS examples / source code, area modifications are performed in controllers. In my directive, I need to get some information from another directive (or its scope) and put it in scope (as seen in the template directive). Since this information is common to all instances of this directive, using region binding is not suitable for me.

So, the only solution I found is to change the scope of the instance in the binding function:

link: function(scope, element, attr, parentCtrl) { scope.data = parentCtrl.someData; } 

This solution works. Plnkr example

Question: Is it good to change the scope of the binding function in accordance with AngularJS philosophy / style, or is there another solution?

+4
source share
2 answers

Since you are isolating areas in your directives (in your plnkr example), and you want to allow parents to be β€œsomewhere” in the area hierarchy (according to your comment on @MathewBerg), I believe that your only option is to use the bind function to area changes.

(I suppose you could define methods on your MainCtrl that should only respond to child directives, but forced execution would be messy and break encapsulation).

So, to repeat what @MathewBerg already said, yes, change the scope in the directive / link.

+1
source

Modifying the scope in directives is fine. Regarding the exchange of information between directives, there are several methods. One of them is how you described when you go to the parents controller and get his data, another very similar method would be to

 scope.data = scope.$parent.data; 

Instead

 scope.data = parentCtrl.someData; 

A common way to exchange information between directives is to use the service. This will allow you to enter a service in each directive, and they can share values. The problem with your original method (and the one I described) is that if you ever move an element around to change the hierarchy of areas, your code will break. That is why I would recommend using the service for both. I suggest reading in the service documents . There are also many videos describing how to set them up: http://www.youtube.com/watch?v=1OALSkJGsRw

+1
source

All Articles