Angular 1.2 no longer allows multiple isolated sco

2019-02-05 07:13发布

问题:

I have some code in an Angular project that use two separate directives with isolated scope. They do not need to share scope, simply exist on the same element. They both alter the DOM in slightly different ways, and importantly bind to values passed as arguments.

This worked in 1.0, however Angular 1.2 now generates an error when attempting to do this

Multiple directives asking for new/isolated scope

Based on the projects git history appears Angular 1.2 changes behaviour to keep two isolated directives on the same element separate. This is a good thing, and it works correctly when putting two 'Attribute' directives on the same element.

i.e.

<div my:directive="myDirectiveData" my:other-directive="myOtherDirectiveData" />

works as you would expect.

however

<my:directive my:directive-data="myDirectiveData" my:other-directive="myOtherDirectiveData" />

Throws the above error. (Multiple directives asking for new/isolated scope)

In this scenario I would have expected each directive to still exist in parallel with their own unshared isolated scope.

Is this still possible in Angular 1.2?

回答1:

Summary of what happens when multiple directives are defined on the same element:

  Scenario  directive #1   directive #2   Result
     1      no new scope   no new scope   Both directives use the controller's scope.
                                          (This should be obvious.)
     2      new scope      new scope      Both directives share one new child scope.
     3      new scope      no new scope   Both directives share one new child scope.
                                          Why does dir #2 use the child scope?
                                          This seems odd to me.
     4      isolate scope  no new scope   Angular v1.0: both directives share the
                                          isolate scope.
                                          Angular v1.2+: dir #1 uses the isolate scope,
                                          dir #2 uses the controller's scope.

Note that the following scenarios are not allowed (Angular throws an error):

  Scenario  directive #1   directive #2
     5      isolate scope  new scope
     6      isolate scope  isolate scope


回答2:

You can't have multiple directives asking for isolate scope on the same element. I think your problem may be caused by this unresolved issue in angularjs.