Can't access controller scope from angular component output binding function
I'm trying to access my home controller scope from dashboard component but it's undefined.
I also tried a second approach but then my function variable is undefined.
I'm using Angular 1.5 with Typescript
FIRST APPROACH:
Home controller HTML:
<div class="home-container">
<dashboard-component on-tile-type-changed="HomeCtrl.onTileTypeChanged">
</dashboard-component>
</div>
Home controller js:
namespace app.dashboard {
'use strict';
class HomeController {
static $inject:Array<string> = ['$window'];
constructor(private $window:ng.IWindowService) {
}
private onTileTypeChanged(tile:ITile) {
console.log(tile); // DEFINED AND WORKING
console.log(this); // NOT DEFINED
}
}
angular
.module('app.dashboard')
.controller('HomeController', HomeController);
}
Dashboard controller js:
angular.module('app.dashboard')
.component('dashboardComponent', {
templateUrl: 'app/dashboard/directives/dashboard-container.html',
controller: DashboardComponent,
controllerAs: 'DashboardCtrl',
bindings: {
onTileTypeChanged: "&"
}
});
this.onTileTypeChanged()(tile);
SECOND APPROACH:
Home controller HTML:
<div class="home-container">
<dashboard-component on-tile-type-changed="HomeCtrl.onTileTypeChanged()">
</dashboard-component>
</div>
Dashboard controller js:
this.onTileTypeChanged(tile);
And here I'm getting the opposite:
private onTileTypeChanged(tile:ITile) {
console.log(tile); // NOT DEFINED
console.log(this); // DEFINED AND WORKING
}
tl;dr; see Demo below
You are using expression binding.
To communicate event data from a component to a parent controller:
Instantiate the
dashboard-component
with:In the component controller invoke the function with locals:
The convention for injected locals is to name them with a
$
prefix to differentiate them from variables on parent scope.From the Docs:
-- AngularJS Comprehensive Directive API Reference
DEMO of using expression (
"&"
) binding to pass data