3

I can watch in a directive one object's property (actually - clientHeight). But how to change other object's padding-top according to this height? I know how to do this using jQuery, but I am looking for an Angular way.

In Angular one can access some page element using a directive. Ok, but how to access other page element in the same directive?

0

1 Answer 1

5

There are a number of ways you could do this. For all of the suggestions below, assume you have two directives – one for watching the clientHeight, the other for adjusting the padding.

  • Create a service (that is injected into both directives). Have the first directive modify an object property in the service (e.g., someObj.prop1). The other directive $watches that object property.
  • Use events. Have the first directive $emit or $broadcast an event and the second directive can listen for it using $on (in its link function or in its own controller).
  • If there is an ancestor relationship, you can require the ancestor directive's controller in the descendant directive. See AngularJS: reuse component with different parent for an example.

  • Not recommended, but another option: use $rootScope instead of a service: inject $rootScope into both directives. Have the first directive modify an object property on $rootScope. The other directive $watches that object property.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Which method would you prefer if you were to do this in your application and why?
@Trevor, if the two elements on which the directives are used are related and always/naturally have an ancestor-descendant relationship, I'd go with require. If there may be (now or in the future) some additional information sharing going on between these directives, a service. If this is a one-off get-it-done-quick app, or I'm feeling lazy, $rootScope or events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.