Wednesday, 15 February 2012

How to chain nested directives which use isolated scopes in angularjs -



How to chain nested directives which use isolated scopes in angularjs -

i'm trying chain 2 nested directives both utilize isolated scopes.

<div ng-controller="mycontroller"> <my-dir on-done="done()"> <my-dir2 on-done="done()"> </my-dir2> </my-dir> </div>

i sec directive (my-dir2) phone call done() function of first directive (my-dir) in turn phone call controller one.

unfortunately don't know how create sec directive access callback of first directive (so far sec directive looking within high level controller, bypassing first directive).

i think 1 perchance create utilize of "require" can't since 2 directives not related (i want utilize my-dir2 within other directives not my-dir).

to create clear : don't want utilize require because means there dependency of mydir on mydir2. point : want able reuse mydir2 within others directives. don't want mydir2 based on mydir want inform upper directive (mydir) when done (like in callback in js).

i have made plunker : can see in javascript console, my-dir2 calling straight done function high level controller.

does has clean way deal kind of situation ?

thanks

update:

to able write directives independent of each other need utilize events:

use $emit('myevent', 'mydata') fire event handled scopes upward in hierarchy. use $broadcast('myevent', 'mydata') fire event handled scopes downward in hierarchy. to handle event fired $emit or $broadcast utilize $on('myevent', function(event, data){\\your code})

p.s.: in case $emit won't work because both directives scopes on same level in hierarchy need utilize $rootscope.$broadcast('myevent' \*, mydata*\); i've updated plunker reflect needed changes http://plnkr.co/edit/etko6sk6hpuypncjlskn?p=info

the next create inner directive dependent on outer directive:

basically able phone call function in first directive need changes:

add require = '^mydir' mydir2 remove ondone mydir2 , maintain isolated scope scope:{} add controller parameter link function in mydir2 link: function(scope,element,attrs,controller) in mydir1 controller alter definition of done function $scope.done this.done call controller.done() in mydir2

here plunker needed changes http://plnkr.co/edit/etko6sk6hpuypncjlskn

angularjs

No comments:

Post a Comment