Snedden27
Snedden27

Reputation: 1930

Should I use events or function binding in angular for components to talk to each other

Which is recommended :

Parent template:

<parent>
 <child-component "doSomethingFunction = $ctrl.referrencedDoSomethingFunction()">
</parent>

Child component:

child_component = {
                controller: childController,
                require: {
                    parentCtrl: '^^parentComponentCtrl'
                },
                bindings: {
                    doSomethingFunction: '&',
                },
                template:childTemplate
            };

OR

<parent>
 <child-component>
</parent>

Parent controller:

$scope.$on('somethingHappened',  function (event, data) {
                //doSomething now..
            });)

Child controller:

  $scope.$emit('somethingHappened')

Not sure if one is better than the other , one reason I think function binding might be better is that it gives a API in form of binding so the user of the component might know what is need before he uses the component.

But is one way recommended than the other?

Upvotes: 0

Views: 46

Answers (1)

Petr Averyanov
Petr Averyanov

Reputation: 9476

  1. In general prefer function binding. Components with clear input and output are easy to read and use.

  2. When this leads to lots of extra code - when you want pass something from very bottom component to parent like 3-4 leves, you may consider using events. But this is quite rare case.

Upvotes: 1

Related Questions