Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Yet Angular allows you to create a scope for the directive itself, such as with { scope: true }. If you do this, when are you supposed to initialize like you would in your controller constructor -- in the post-link function? That seems like an inappropriate use of the directive, since it's not concerned with the DOM.</p> </blockquote> <p>A directive can have its own controller, defined by the <code>controller</code> option. That controller has the same function as an application controller: to provide behavior for the directive. That said, I think the correct place to initialize the scope is the directive's controller, not its link function. </p> <p>I think of a directive's controller as the place where you manipulate the scope and of the directive's link function as the place you manipulate the DOM. This <a href="https://stackoverflow.com/questions/18198592/behavior-of-controller-inside-directives">SO question</a> has some good insights on that matter.</p> <blockquote> <p>When is it appropriate to use an Angular directive scope instead of creating a controller that must be used with that directive instead?</p> </blockquote> <p>Off the top of my head I can think of two scenarios:</p> <ul> <li>You want your directive to access its parent scope, but don't want it to modify the parent scope's data. In order to do that you need to set the directive to have its own scope, i.e. <code>scope: true</code>. </li> <li>You want your directive to be reusable. In such a case, the directive shouldn't rely on any parent scope, and should have its own isolate scope, i.e, <code>scope: {}</code>.</li> </ul> <p>I've implemented a directive recently and used the controller function for driving its behavior and the link function for manipulating the DOM. Perhaps you'd be interested in checking it out. Link <a href="https://github.com/mbenford/ngTagsInput" rel="nofollow noreferrer">here</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload