Using expression `("&")` binding to pass data from AngularJS component to parent scope Using expression `("&")` binding to pass data from AngularJS component to parent scope angularjs angularjs

Using expression `("&")` binding to pass data from AngularJS component to parent scope


tl;dr; see Demo below

You are using expression binding.

angular.module('app.dashboard')    .component('dashboardComponent', {        templateUrl: 'app/dashboard/directives/dashboard-container.html',        controller: DashboardComponent,        controllerAs: 'DashboardCtrl',        bindings: {            onTileChange: "&"        }    })t

To communicate event data from a component to a parent controller:

Instantiate the dashboard-component with:

<dashboard-component on-tile-change="HomeCtrl.onTileChange($tile)"></dashboard-component>

In the component controller invoke the function with locals:

this.onTileChange({$tile: tile});

The convention for injected locals is to name them with a $ prefix to differentiate them from variables on parent scope.

From the Docs:

  • & or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <my-component my-attr="count = count + value"> and the isolate scope definition scope: { localFn:'&myAttr' }, the isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope. This can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment($amount) then we can specify the amount value by calling the localFn as localFn({$amount: 22}).

-- AngularJS Comprehensive Directive API Reference


DEMO of using expression ("&") binding to pass data

angular.module("app",[]).directive("customDirective",function() {    return {        scope: {            onSave: '&',        },        template: `            <fieldset>                <input ng-model="message"><br>                <button ng-click="onSave({$event: message})">Save</button>            </fieldset>        `,    };})
<script src="//unpkg.com/angular/angular.js"></script><body ng-app="app">    <custom-directive on-save="message=$event">    </custom-directive>    <br>    message={{message}}</body>