Directive isolate scope with ng-repeat scope in AngularJS

55,558

Solution 1

Okay, through a lot of the comments above, I have discovered the confusion. First, a couple of points of clarification:

  • ngRepeat does not affect your chosen isolate scope
  • the parameters passed into ngRepeat for use on your directive's attributes do use a prototypically-inherited scope
  • the reason your directive doesn't work has nothing to do with the isolate scope

Here's an example of the same code but with the directive removed:

<li ng-repeat="name in names"
    ng-class="{ active: $index == selected }"
    ng-click="selected = $index">
    {{$index}}: {{name.first}} {{name.last}}
</li>

Here is a JSFiddle demonstrating that it won't work. You get the exact same results as in your directive.

Why doesn't it work? Because scopes in AngularJS use prototypical inheritance. The value selected on your parent scope is a primitive. In JavaScript, this means that it will be overwritten when a child sets the same value. There is a golden rule in AngularJS scopes: model values should always have a . in them. That is, they should never be primitives. See this SO answer for more information.


Here is a picture of what the scopes initially look like.

enter image description here

After clicking the first item, the scopes now look like this:

enter image description here

Notice that a new selected property was created on the ngRepeat scope. The controller scope 003 was not altered.

You can probably guess what happens when we click on the second item:

enter image description here


So your issue is actually not caused by ngRepeat at all - it's caused by breaking a golden rule in AngularJS. The way to fix it is to simply use an object property:

$scope.state = { selected: undefined };
<li ng-repeat="name in names"
    ng-class="{ active: $index == state.selected }"
    ng-click="state.selected = $index">
    {{$index}}: {{name.first}} {{name.last}}
</li>

Here is a second JSFiddle showing this works too.

Here is what the scopes look like initially:

enter image description here

After clicking the first item:

enter image description here

Here, the controller scope is being affected, as desired.

Also, to prove that this will still work with your directive with an isolate scope (because, again, this has nothing to do with your problem), here is a JSFiddle for that too, the view must reflect the object. You'll note that the only necessary change was to use an object instead of a primitive.

Scopes initially:

enter image description here

Scopes after clicking on the first item:

enter image description here

To conclude: once again, your issue isn't with the isolate scope and it isn't with how ngRepeat works. Your problem is that you're breaking a rule that is known to lead to this very problem. Models in AngularJS should always have a ..

Solution 2

Without directly trying to avoid answering your questions, instead take a look at the following fiddle:

http://jsfiddle.net/dVPLM/

Key point is that instead of trying to fight and change the conventional behaviour of Angular, you could structure your directive to work with ng-repeat as opposed to trying to override it.

In your template:

    <name-row 
        in-names-list="names"
        io-selected="selected">
    </name-row>

In your directive:

    template:
'        <ul>' +      
'            <li ng-repeat="name in inNamesList" ng-class="activeClass($index)" >' +
'                <a ng-click="setSelected($index)">' +
'                    {{$index}} - {{name.first}} {{name.last}}' +
'                </a>' +
'            </li>' +
'        </ul>'

In response to your questions:

Share:
55,558
Deepak Nulu
Author by

Deepak Nulu

Updated on July 10, 2020

Comments

  • Deepak Nulu
    Deepak Nulu almost 4 years

    I have a directive with an isolate-scope (so that I can reuse the directive in other places), and when I use this directive with an ng-repeat, it fails to work.

    I have read all the documentation and Stack Overflow answers on this topic and understand the issues. I believe I have avoided all the usual gotchas.

    So I understand that my code fails because of the scope created by the ng-repeat directive. My own directive creates an isolate-scope and does a two-way data-binding to an object in the parent scope. My directive will assign a new object-value to this bound variable and this works perfectly when my directive is used without ng-repeat (the parent variable is updated correctly). However, with ng-repeat, the assignment creates a new variable in the ng-repeat scope and the parent variable does not see the change. All this is as expected based on what I have read.

    I have also read that when there are multiple directives on a given element, only one scope is created. And that a priority can be set in each directive to define the order in which the directives are applied; the directives are sorted by priority and then their compile functions are called (search for the word priority at http://docs.angularjs.org/guide/directive).

    So I was hoping I could use priority to make sure that my directive runs first and ends up creating an isolate-scope, and when ng-repeat runs, it re-uses the isolate-scope instead of creating a scope that prototypically inherits from the parent scope. The ng-repeat documentation states that that directive runs at priority level 1000. It is not clear whether 1 is a higher priority level or a lower priority level. When I used priority level 1 in my directive, it did not make a difference, so I tried 2000. But that makes things worse: my two-way bindings become undefined and my directive does not display anything.

    I have created a fiddle to show my issue. I have commented out the priority setting in my directive. I have a list of name objects and a directive called name-row that shows the first and last name fields in the name object. When a displayed name is clicked, I want it to set a selected variable in the main scope. The array of names, the selected variable are passed to the name-row directive using two-way data-binding.

    I know how to get this to work by calling functions in the main scope. I also know that if selected is inside another object, and I bind to the outer object, things would work. But I am not interested in those solutions at the moment.

    Instead, the questions I have are:

    • How do I prevent ng-repeat from creating a scope that prototypically inherits from the parent scope, and instead have it use my directive's isolate-scope?
    • Why is priority level 2000 in my directive not working?
    • Using Batarang, is it possible to know what type of scope is in use?
  • Deepak Nulu
    Deepak Nulu about 11 years
    Thank you for such a quick response. If what I am attempting goes against the grain, I am a bit saddened (AngularJS is nonetheless an awesome framework). A directive is meant to be a reusable component. When it is written, the author should not have to worry about whether it will be used with an ng-repeat or not. Maybe when it is first written, it is never used with ng-repeat. And some time in the future, it might get used with ng-repeat, and at that point in time, it should just work without a rewrite. Hopefully a future release of AngularJS will make this possible.
  • Deepak Nulu
    Deepak Nulu about 11 years
    I would like to clarify my comment above. I think it is possible to write a directive that does not worry about whether it is being used with ng-repeat or not. But it appears that I would have to pass in a function to the directive so that it can modify the variables in the parent scope, instead of being able to mutate a two-way binding in the directive's own scope. Two-way binding and reusable directives are my top two favorite things about AngularJS and ng-repeat is proving to be a fly in the ointment. Maybe I can write an ng-repeat equivalent that does not create its own scope.
  • Deepak Nulu
    Deepak Nulu about 11 years
    My experiments with directives with isolate-scopes and 2-way data binding lead me to believe that the . golden rule is only required for scopes that have prototypical inheritance. With isolate-scopes, the variables you are interested in are defined in the scope: {} definition in the directive, and therefore those variables will exist in the isolate-scope from the beginning. Also, they don't mask the parent variables because the isolate-scope does not prototypically inherit from the parent scope. i.e. there is no "parent" scope to mask.
  • Deepak Nulu
    Deepak Nulu about 11 years
    But updating a two-way bound variable in the isolate-scope (defined with = in scope: {}) causes the corresponding variable in the outer scope to change because of the two-way data binding. I can't remember trying this out with primitive variables in the isolate-scope, but I have definitely seen this working with object/reference variables. Note that I am talking about assigning a new object value to the variable, not modifying a property inside the object. i.e. I am not following the . golden rule in my directive and it still works.
  • Deepak Nulu
    Deepak Nulu about 11 years
    I have forked my fiddle and replaced the ng-repeat with a manual repetition: jsfiddle.net/jtjk4/1 (I created variables for each index in MainController because my directive uses an inIndex : '=' binding for the index). You will see that this works fine. My directive assigns a new value to ioSelected without using . and it works correctly (the outer scope sees the change and displays the selected name in the HTML output). This is what leads me to say that it is ng-repeat (specifically its scope) that breaks my two-way data-bound isolate-scope directive. What am I missing?
  • Deepak Nulu
    Deepak Nulu about 11 years
    I also have cases where I have nested directives, all with isolate-scopes and two-way data-binding in them. The values bound to my outer-directive need to be passed to my inner-directive. Requiring a wrapper object (so that I can follow the . golden rule) becomes a leaky abstraction that forces me to rewrite my directives.
  • Deepak Nulu
    Deepak Nulu about 11 years
    To me, this means the promise of directives as standalone components is broken. Please note that I am aware of all the solutions mentioned so far and I am passing functions to my directives to overcome this issue. But I feel very strongly that there needs to be a better solution that will let us realize the full potential of directives and two-way data binding. </response>
  • Josh David Miller
    Josh David Miller about 11 years
    It really has nothing to do with your isolate scope or with your directive. Nothing. ngRepeat must create its own scope to work properly; so will any number of other components. Meaning even if you wrote your own frailer version of ngRepeat to force it to work for you in your case, it will similarly break in plenty of other cases (e.g. transclusion). And you're doing it just to break a rule! In AngularJS, you always include a .. When you don't, you're making it frail and it will eventually stop working. What I really don't get is why you're resisting it in the first place.
  • Josh David Miller
    Josh David Miller about 11 years
    Should have also said: your directive isn't creating a child scope, but it could easily be used in a context that requires a child scope. ngRepeat is one case. So is transclusion. Trust me - use the ..
  • Deepak Nulu
    Deepak Nulu about 11 years
    Discussion on the AngularJS Google Group where @JoshDavidMiller was finally able to clear my confusion!
  • Jeff Voss
    Jeff Voss over 10 years
    How did you guys make those charts? they are awesome
  • Asad Saeeduddin
    Asad Saeeduddin about 10 years
    Where do you guys get all these cool diagrams from? I've seen another user posting these as well.
  • Mark Rajcok
    Mark Rajcok about 9 years
    @Asad, I just recently put the tool up on GitHub, it's called Peri$scope.