Directive isolate scope with ng-repeat scope in AngularJS
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.
After clicking the first item, the scopes now look like this:
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:
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:
After clicking the first item:
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:
Scopes after clicking on the first item:
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:
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:
-
ng-repeat
will create a scope, you really shouldn't be trying to change this. - Priority in directives isn't just execution order - see: AngularJS : How does the HTML compiler arrange the order for compiling?
- In Batarang, if you check the performance tab, you can see the expressions bound for each scope, and check if this matches your expectations.
Deepak Nulu
Updated on July 10, 2020Comments
-
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 withoutng-repeat
(the parent variable is updated correctly). However, withng-repeat
, the assignment creates a new variable in theng-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. Theng-repeat
documentation states that that directive runs at priority level1000
. It is not clear whether1
is a higher priority level or a lower priority level. When I used priority level1
in my directive, it did not make a difference, so I tried2000
. But that makes things worse: my two-way bindings becomeundefined
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 calledname-row
that shows the first and last name fields in the name object. When a displayed name is clicked, I want it to set aselected
variable in the main scope. The array of names, theselected
variable are passed to thename-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?
- How do I prevent
-
Deepak Nulu about 11 yearsThank 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 withng-repeat
. And some time in the future, it might get used withng-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 about 11 yearsI 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 andng-repeat
is proving to be a fly in the ointment. Maybe I can write anng-repeat
equivalent that does not create its own scope. -
Deepak Nulu about 11 yearsMy 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 thescope: {}
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 about 11 yearsBut updating a two-way bound variable in the isolate-scope (defined with
=
inscope: {}
) 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 about 11 yearsI have forked my fiddle and replaced the
ng-repeat
with a manual repetition: jsfiddle.net/jtjk4/1 (I created variables for each index inMainController
because my directive uses aninIndex : '='
binding for the index). You will see that this works fine. My directive assigns a new value toioSelected
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 isng-repeat
(specifically its scope) that breaks my two-way data-bound isolate-scope directive. What am I missing? -
Deepak Nulu about 11 yearsI 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 about 11 yearsTo 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 about 11 yearsIt 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 about 11 yearsShould 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 about 11 yearsDiscussion on the AngularJS Google Group where @JoshDavidMiller was finally able to clear my confusion!
-
Jeff Voss over 10 yearsHow did you guys make those charts? they are awesome
-
Asad Saeeduddin about 10 yearsWhere do you guys get all these cool diagrams from? I've seen another user posting these as well.
-
Mark Rajcok about 9 years@Asad, I just recently put the tool up on GitHub, it's called Peri$scope.