I have some data called foo which lives in a scope which is parent to three children:
<div ng-init="foo=[1, 2, 3]">
<bar foo="{{foo}}" baz="{{odp}}" />
<mpq foo="{{foo}}" bats="{{maktz}}" />
<ktr foo="{{foo}}" otr="{{ompg}}" />
</div>
bar.scope = {foo: '=', baz: '@'};
mpq.scope = {foo: '=', bats: '@'};
ktr.scope = {foo: '=', otr: '@'};
What is the best way to share foo between those three directives? Options include:
- Use an isolated scope to pass in
foothree times, thereby duplicating it across four scopes - Have the child directives inherit the parent scope, and find
baz,bats, orotronattrs - Put
fooon the$rootScopeand inject that into the child directives
Or is there another approach that is better?
You can create a factory that you can pass to each directive or controller. That will make sure you only have one instance of the array at any given time. EDIT: The only gotcha here is to make sure you’re setting reference types and not primitive types on your directive scopes, or you’ll end up duplicating the values in each scope.
Here is an example on Plnkr.co
HTML