Skip to main content

[SOLVED] Angularjs components – How to pass-in arguments in callbacks

It’s pretty straightforward but not very clear in the documentation, so how do you pass-in arguments in a callback in an Angular component? In your Angular component you have to bind your callback with ‘&’ and return an object with the passed-in name as key:

Angular-component.html

<my-component callback="$ctrl.callback(keyName)"></my-component>

Angular-template.html

<button ng-click="$ctrl.save({'foo':'bar'})">Pass object to callback</button>

Angular-component-and-controller.js

 angular
    .module('app')
    .controller('myController', MyController)
    .component('myComponent', {
        templateUrl: '/Angular-template.html',
        controller: 'myController',
        bindings: {
           callback: '&'
        }
 });

function MyController() {
   var $ctrl = this;
   $ctrl.save = function (data) {
      $ctrl.callback({keyName:data});
   };
}

The important part is of course the ‘&’ binding but also the key name marked with bold in the example.

Leave a Reply

Your email address will not be published. Required fields are marked *