konapun konapun - 1 year ago 63
AngularJS Question

Rebinding this on angular callback from inside link funtion

I have a directive similar to this this:

app.directive('example', function() {
return {
restrict: 'E',
transclude: true,
scope: {
callback: '&'
template: '<span ng-click="example.callback()">Click Me</span>',
bindToController: true,
controllerAs: 'example',
controller: function() {
this.counter = 0;

this.incrementCount = function() {

this.getCount = function() {
return this.counter;
link: function(scope, el, attrs, ctrl) {
var oldCallback = scope.callback;
ctrl.callback = function() {
return oldCallback.call(ctrl); // I want to be able to use `this` as the controller to access the API from within the callback

with a controller

app.controller("ctrl", ["$scope", function(s) {
s.callback = function() {
console.log("Value: " + this.getCount());

And view

<div ng-app="app">
<div class="container" ng-controller="ctrl">
<example callback="callback()"></example>


When I log ctrl in within the ctrl.callback in the link function it logs the example controller as I expect but when oldCallback is called, it doesn't get ctrl rebound to
as I want. Is there any way to access the API defined in the directive's controller from within the callback on the scope while still using an isolate scope for the directive?

rob rob
Answer Source

You could pass the directives controller out through the callback. e.g.

example html

<span ng-click="example.callback({$exampleCtrl:example})">Click Me</span>

index html

<example callback="callback($exampleCtrl)"></example>


$scope.callback = function($exampleCtrl) {
    console.log("Value: " + $exampleCtrl.getCount());


Also note that bindToController is only supported in AngularJs 1.3+ and your code pen was using 1.2