ChatGPT解决这个技术问题 Extra ChatGPT

When writing a directive in AngularJS, how do I decide if I need no new scope, a new child scope, or a new isolated scope?

I'm looking for some guidelines that one can use to help determine which type of scope to use when writing a new directive. Ideally, I'd like something similar to a flowchart that walks me through a bunch of questions and out pops the correct answer – no new new scope, new child scope, or new isolate scope – but that is likely asking for too much. Here's my current paltry set of guidelines:

Don't use an isolated scope if the element that will use the directive uses ng-model See Can I use ng-model with isolated scope? and Why formatters does not work with isolated scope?

If the directive doesn't modify any scope/model properties, don't create a new scope

Isolate scopes seem to work well if the directive is encapsulating a set of DOM elements (the documentation says "a complex DOM structure") and the directive will be used as an element, or with no other directives on the same element.

I'm aware that using a directive with an isolated scope on an element forces all other directives on that same element to use the same (one) isolate scope, so doesn't this severely limit when an isolate scope can be used?

I am hoping that some from the Angular-UI team (or others that have written many directives) can share their experiences.

Please don't add an answer that simply says "use an isolated scope for reusable components".

by "child scope" you mean creating scope in link function by "scope.$new()"? Because I as know, directive can have isolated scope or do not have it (so will be using scope where is been used)
@ValentynShybanov Setting scope: true will create a child scope using $scope.new() automatically.
@Valentyn, what Josh said: so, the three possibilities are scope: false (the default, no new scope), scope: true (new scope that inherits prototypically), and scope: { ... } (new isolate scope).
Yes, thnx. I've missed that difference between "true" and "{}". Good to know.
There is a 4th case which people generally tend to ignore.. that is the "directive controller".. I think the question should be expanded to include them as well... +1 to the question..

J
Josh David Miller

What a great question! I'd love to hear what others have to say, but here are the guidelines I use.

The high-altitude premise: scope is used as the "glue" that we use to communicate between the parent controller, the directive, and the directive template.

Parent Scope: scope: false, so no new scope at all

I don't use this very often, but as @MarkRajcok said, if the directive doesn't access any scope variables (and obviously doesn't set any!) then this is just fine as far as I am concerned. This is also helpful for child directives that are only used in the context of the parent directive (though there are always exceptions to this) and that don't have a template. Basically anything with a template doesn't belong sharing a scope, because you are inherently exposing that scope for access and manipulation (but I'm sure there are exceptions to this rule).

As an example, I recently created a directive that draws a (static) vector graphic using an SVG library I'm in the process of writing. It $observes two attributes (width and height) and uses those in its calculations, but it neither sets nor reads any scope variables and has no template. This is a good use case for not creating another scope; we don't need one, so why bother?

But in another SVG directive, however, I required a set of data to use and additionally had to store a tiny bit of state. In this case, using the parent scope would be irresponsible (again, generally speaking). So instead...

Child Scope: scope: true

Directives with a child scope are context-aware and are intended to interact with the current scope.

Obviously, a key advantage of this over an isolate scope is that the user is free to use interpolation on any attributes they want; e.g. using class="item-type-{{item.type}}" on a directive with an isolate scope will not work by default, but works fine on one with a child scope because whatever is interpolated can still by default be found in the parent scope. Also, the directive itself can safely evaluate attributes and expressions in the context of its own scope without worrying about pollution in or damage to the parent.

For example, a tooltip is something that just gets added; an isolate scope wouldn't work (by default, see below) because it is expected that we will use other directives or interpolated attributes here. The tooltip is just an enhancement. But the tooltip also needs to set some things on the scope to use with a sub-directive and/or template and obviously to manage its own state, so it would be quite bad indeed to use the parent scope. We are either polluting it or damaging it, and neither is bueno.

I find myself using child scopes more often than isolate or parent scopes.

Isolate scope: scope: {}

This is for reusable components. :-)

But seriously, I think of "reusable components" as "self-contained components". The intent is that they are to be used for a specific purpose, so combining them with other directives or adding other interpolated attributes to the DOM node inherently doesn't make sense.

To be more specific, anything needed for this standalone functionality is provided through specified attributes evaluated in the context of the parent scope; they are either one-way strings ('@'), one-way expressions ('&'), or two-way variable bindings ('=').

On self-contained components, it doesn't make sense to need to apply other directives or attributes on it because it exists by itself. Its style is governed by its own template (if necessary) and can have the appropriate content transcluded (if necessary). It's standalone, so we put it in an isolate scope also to say: "Don't mess with this. I'm giving you a defined API through these few attributes."

A good best practice is to exclude as much template-based stuff from the directive link and controller functions as possible. This provides another "API-like" configuration point: the user of the directive can simply replace the template! The functionality all stayed the same, and its internal API was never touched, but we can mess with styling and DOM implementation as much as we need to. ui/bootstrap is a great example of how to do this well because Peter & Pawel are awesome.

Isolate scopes are also great for use with transclusion. Take tabs; they are not only the whole functionality, but whatever is inside of it can be evaluated freely from within the parent scope while leaving the tabs (and panes) to do whatever they want. The tabs clearly have their own state, which belongs on the scope (to interact with the template), but that state has nothing to do with the context in which it was used - it's entirely internal to what makes a tab directive a tab directive. Further, it doesn't make much sense to use any other directives with the tabs. They're tabs - and we already got that functionality!

Surround it with more functionality or transclude more functionality, but the directive is what it is already.

All that said, I should note that there are ways around some of the limitations (i.e. features) of an isolate scope, as @ProLoser hinted at in his answer. For example, in the child scope section, I mentioned interpolation on non-directive attributes breaking when using an isolate scope (by default). But the user could, for example, simply use class="item-type-{{$parent.item.type}}" and it would once again work. So if there is a compelling reason to use an isolate scope over a child scope but you're worried about some of these limitations, know that you can work around virtually all of them if you need to.

Summary

Directives with no new scope are read-only; they're completely trusted (i.e. internal to the app) and they don't touch jack. Directives with a child scope add functionality, but they are not the only functionality. Lastly, isolate scopes are for directives that are the entire goal; they are standalone, so it's okay (and most "correct") to let them go rogue.

I wanted to get my initial thoughts out, but as I think of more things, I'll update this. But holy crap - this is long for an SO answer...

PS: Totally tangential, but since we're talking about scopes, I prefer to say "prototypical" whereas others prefer "prototypal", which seems to be more accurate but just rolls off the tongue not at all well. :-)


Thanks Josh, great answer. I wanted/expected long answers for this. Two things I didn't follow: 1) child scope: "the user is free to use interpolation on any attributes they want". 2) isolate scope: "or not all, in the case of '?'" Can you elaborate a bit on those? (Feel free to edit your post instead of writing comments if that is easier.)
@MarkRajcok For (1), I changed it to make it a little less nebulous - let me know if I was unsuccessful. For (2), that was a combination of a typo and poor wording; I rewrote that paragraph to be clearer. I also added an additional example or two, clarified a few more things, and fixed some typos.
As mentioned in the answer - bootstrap for angular is a great example of combining these. I found the accordion example particularly useful - GitHub - Accordion
You mentioned that you use child scopes the most, I thought that the reusable pattern of directives was the most common and I have avoided writing directives that were meant only to be used once. Is this un-needed? Sometimes when my HTML gets too large I feel like moving that section into a directive but it'll only be used once so I just leave it in the html.
@user2483724 A very common misconception is that "reusable" directives are ones that use an isolate scope; not so. If you look at the pre-packaged directives, nearly none of them use isolate scopes - some not even a child scope - but I assure you they're reusable! The rule should be in how the scope within the directive is used. If it's just about saving space in a file, I'm not sure a directive is the best approach. It increases processing time for the sake of the developer. But if you must, then go for it. Or use an ngInclude. Or do it as part of your build. Many options!
P
ProLoser

My personal policy and experience:

Isolated: a private sandbox

I want to create a lot of scope methods and variables that are ONLY used by my directive and are never seen or directly accessed by the user. I want to whitelist what scope data is available to me. I can use transclusion to allow the user to jump back in at the parent scope (unaffected). I do NOT want my variables and methods accessible in transcluded children.

Child: a subsection of content

I want to create scope methods and variables that CAN be accessed by the user, but are not relevant to surrounding scopes (siblings and parents) outside the context of my directive. I also would like to let ALL parent scope data to trickle down transparently.

None: simple, read-only directives

I don't really need to mess with scope methods or variables. I'm probably doing something that doesn't have to do with scopes (such as displaying simple jQuery plugins, validation, etc).

Notes

You should not let ngModel or other things directly impact your decision. You can circumvent odd behavior by doing things like ng-model=$parent.myVal (child) or ngModel: '=' (isolate).

Isolate + transclude will restore all normal behavior to sibling directives and returns to the parent scope, so don't let that affect your judgement either.

Don't mess with the scope on none because it's like putting data on scope for the bottom half of the DOM but not the top half which makes 0 sense.

Pay attention to directive priorities (don't have concrete examples of how this can affect things)

Inject services or use controllers to communicate across directives with any scope type. You can also do require: '^ngModel' to look in parent elements.


I may have misunderstood this part: "Isolate + transclude will restore all normal behavior to sibling directives". See this plunker. You'll have to look in the console.
Thanks ProLoser for your insights/answer. You are one of the people I hoped would see this post if I added the angularjs-ui tag.
@JoshDavidMiller when talking about directives on the same DOM element things get more complicated, and you should start taking a look at the priority property instead. Transclusion is more relevant to children contents.
@ProLoser Right, but I'm not sure what you meant by that statement. They obviously affect children, but how do scopes of directives affect their sibling directives at all?
U
Umur Kontacı

After writing a lot of directives, I've decided to use less isolated scope. Even though it is cool and you encapsulate the data and be sure not to leak data to the parent scope, it severely limits the amount of directives you can use together. So,

If the directive you're going to write is going to behave entirely on its own and you are not going to share it with other directives, go for isolated scope. (like a component you can just plug it in, with not much customization for the end developer) (it gets very trickier when you try to write sub-elements which have directives within)

If the directive you're going to write is going to just make dom manipulations which has needs no internal state of scope, or explicit scope alterations (mostly very simple things); go for no new scope. (such as ngShow, ngMouseHover, ngClick, ngRepeat)

If the directive you're going to write needs to change some elements in parent scope, but also needs to handle some internal state, go for new child scope. (such as ngController)

Be sure to check out the source code for directives: https://github.com/angular/angular.js/tree/master/src/ng/directive
It greatly helps on how to think about them


If several components needs to communicate with each other, they can have isolated scope and use require, so keeping your directives still decoupled. So how it limits possibilities? It even more makes directives more specific (so declare what you're depend on). So I would leave only one rule: if your directive has state or needs some data from scope where it is used - use isolated scope. Otherwise do not use scope. And about "child scopes" - I've also wrote quite a lot directives and never needed this feature. If "needs to change some elements in parent scope" - use bindings.
And also about "needs to change some elements in parent scope" - if you modify something in child scope changes are not populated to parent scope (unless you use dirty $parent hack). So actually "child scopes" for directives is something that looks like should be used quite rear - like ngRepeat that creates new child scopes for each item to repeat (but it also creates it using scope.$new(); and not scope: true.
You cannot ask for multiple isolated scopes within the same element, you cannot access to the functions in the parent scope, unless you bind them explicitly. (Good luck using ngClick etc.) Requiring creates a kind of decoupling I agree, but you still need to aware of the parent directive. Unless it is like a component, I'm against going for isolation. Directives (at least, most of them) are meant to be highly reusable and isolation breaks this.
I also don't use child scope's in directives but since a child scope prototypically inherit from the parent scope, if the access to a property within a property in the parent scope, the changes are populated. Angular's authors talked about it in MTV meetup, it is "good to have a dot somewhere" youtube.com/watch?v=ZhfUv0spHCY
First, I think you're a little too harsh on isolate scopes. I think they have broader applicability than you give them credit for having and that there are ways of avoiding many of the challenges you (correctly) pointed out we face when using them. I also disagree with "not much customization for the end developer" - see my answer for details. That said, your answer was neither bad nor wrong and it did address the question, so I'm not sure why it got down-voted. So, +1.
u
user2483724

Just thought I'd add my current understanding and how it relates to other JS concepts.

Default (e.g. not declared or scope: false)

This is philosophically equivalent to using global variables. Your directive can access everything in the parent controller but it is also affecting them and being affected at the same time.

scope:{}

This is like a module, anything it wants to use needs to be passed in explicitly. If EVERY directive you use is an isolate scope it can be the equivalent of making EVERY JS file you write its own module with a lot of overhead in injecting all the dependencies.

scope: child

This is the middle ground between global variables and explicit passthrough. It's similar to javascript's prototype chain and just extends you a copy of the parent scope. If you create an isolate scope and pass in every attribute and function of the parent scope it is functionally equivalent to this.

The key is that ANY directive can be written ANY way. The different scope declarations are just there to help you organize. You can make everything a module, or you can just use all global variables and be very careful. For ease of maintenance though it's preferable to modularalize your logic into logically coherent parts.There is a balance between an open meadow and a closed jail-house. The reason this is tricky I believe is that when people learn about this they think they are learning about how directives work but actually they are learning about code/logic organization.

Another thing that helped me figure out how directives work is learning about ngInclude. ngInclude helps you include html partials. When I first started using directives I found that you could use it's template option to reduce your code but I wasn't really attaching any logic.

Of course between angular's directives and the work of the angular-ui team I haven't yet had to create my own directive that does anything substantial so my view on this may be completely wrong.


U
Ungallery

I concur with Umur. In theory, isolated scopes sound wonderful and "portable," but in building my app to involve non-trivial functionality I came across the need to incorporate several directives (some nested inside others or adding attributes to them) in order to fully write in my own HTML, which is the purpose of a Domain Specific Language.

In the end, it's too weird to have to pass every global or shared value down the chain with multiple attributes on each DOM invocation of a directive (as is required with isolate scope). It just looks dumb to repeatedly write all that in the DOM and it feels inefficient, even if these are shared objects. It also unnecessarily complicates the directive declarations. The workaround of using $parent to "reach up" and grab values from the directive HTML seems like Very Bad Form.

I, too, wound up changing my app to have mostly child scope directives with very few isolates -- only those which don't need to access ANYTHING from the parent other than what they can be passed through simple, non-repetitive attributes.

Having dreamed the dream of Domain Specific Languages for decades before there was such a thing, I'm elated that AngularJS provides this option and I know that, as more devs work in this area, we're going to see some very cool apps that are also easy for their architects to write, expand, and debug.

-- D