1

How to access angular component events in Parent controller Angular JS,

I have an angular component with button click event

is it possible to access/implement these events in Parent controllers?

1
  • Rather than thinking of it as handling an event occurring in the component, what I think you really want to do is call a method on the parent controller from the button click event in your component. Commented Jul 27, 2016 at 20:13

1 Answer 1

4

Instead of accessing child component events, your better option is to pass event using bindings. The true angular way would probably be using "outputs" of the component with callback functions, that child can invoke when necessary. In this case you would kind of use intermediate event mechanism. Implementation-wise it could look like this:

angular.module('demo', [])
  .component('parent', {
    template: `
      <div>
        <child on-select="$ctrl.itemSelected(item)"></child>
      </div>
    `,
    controller() {
      this.itemSelected = function(item) {
        alert(item.name)
      }
    }
  })

  .component('child', {
    bindings: {
      onSelect: '&'
    },
    template: `
      <button ng-click="$ctrl.onSelect({item: {name: 'Thomas'}})">Select</button>
    `
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="demo">
  <parent></parent>
</div>

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for you solution ,it working but I am not getting the argument which passed to the event (always its undefined)
How do you pass this argument?
Got it :) ng-click="vm.onSelect({message:message})" Thanks
This is ok as long as the arguments sent in the event don't change. If they are timing critical and their value at the binding time is not the value wanted, then you may have issues
@LamaanBall The problem of changing/loading values is not really relevant to the described approach and needs to be handles separately anyway. But this is not a problem of input-output I describe in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.