konapun konapun - 4 months ago 22
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.counter++;
};

this.getCount = function() {
return this.counter;
};
},
link: function(scope, el, attrs, ctrl) {
var oldCallback = scope.callback;
ctrl.callback = function() {
console.log(ctrl);
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() {
this.incrementCount();
console.log("Value: " + this.getCount());
};
}]);


And view

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


(codepen)

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
this
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

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>

controller

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

http://codepen.io/anon/pen/BzqqzV

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