How to bind nested directives that use isolated scopes in angularjs

I am trying to link two nested directives that use isolated scopes.

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

      

I would like the second directive (my-dir2) to call the done () function of the first directive (my-dir), which in turn would call the controller.

Unfortunately, I don't know how to get the second directive to access the callback of the first directive (so far, the second directive scans the high-level controller, bypassing the first directive).

I think it would be possible to use "require", but I cannot, since the two directives are not related (I want to use my-dir2 inside other directives, not just my-dir).

To be clear: I don't want to use require because that means there will be my myDir dependency on myDir2. My point is: I want to be able to reuse myDir2 inside other directives. So I don't want myDir2 to be based on myDir, but I want to tell the top directive (myDir) when something is done (like in a callback in js).

I made a plunker : as you can see in the javascript console, my-dir2 calls the directly executed function from a high-level controller.

Does someone have a clean way to handle this kind of situation?

thank

+3


source to share


2 answers


Update:

to write directives independent of each other, you need to use events:

  • use $emit('myEvent', 'myData')

    to fire an event that will be handled by scopes up in the hierarchy.
  • use $broadcast('myEvent', 'myData')

    to fire an event that will be handled by the scopes down the hierarchy.
  • to handle the event that was fired with $emit

    or $broadcast

    , use$on('myEvent', function(event, data){\\your code})

PS: wo $emit

n't work in your case because both pointer $rootScope.$broadcast('myEvent' \*, myData*\);

scopes are at the same level in the hierarchy, so you will need to use I updated my plunker to reflect the changes needed http://plnkr.co/edit/eTkO6sk6hpuYPnCjlSKn?p=info



The following will make the inner directive dependent on the outer directive :

basically, to be able to call the function in the first directive, you need to make some changes:

  • add require = '^myDir'

    tomyDir2

  • remove onDone

    from myDir2

    and save the isolated area scope:{}

  • add controller parameter for communication function in myDir2

    link: function(scope,element,attrs,controller)

  • in the myDir1

    controller will change the function definition done

    from $scope.done

    tothis.done

  • call controller.done()

    inmyDir2

here is the plucker with the necessary changes http://plnkr.co/edit/eTkO6sk6hpuYPnCjlSKn

0


source


I think you can do something like this: angular.element ('my-Dir') controller ('Mydir') done (); ..



try it!

0


source







All Articles