Pass callback function to directive
Asked Answered
N

4

19

I'm trying to pass a callback function from a controller to a directive.

Here's the callback function code:

$scope.onImageSelect = function(image) {
    alert('SET');
    $scope.card.image = image;
};

Directive usage:

<google-image-search callback="onImageSelect" />

Directive code:

ngmod.directive('directive', function() {
    return {
        templateUrl: '/templates/template.html',
        scope: {
            callback: '&'
        }
    }
});

Callback usage in template:

<a data-ng-click="callback(url)"></a>

However, this gives me the following error:

TypeError: Cannot use 'in' operator to search for 'onImageSelect'

I've seen a lot of similar questions, but could not understand where am I wrong.

Neille answered 15/7, 2015 at 20:26 Comment(2)
I'm not sure what you're asking... how is that callback triggered? What is callback(url)?Materialist
onImageSelect should be a function onImageSelect() not a variableImprovement
S
30

While calling the expression method from the directive you need to pass the parameter from the directive in JSON format, also you should correct your directive callback attribute value to pass function like callback="onImageSelect(image)"

Directive usage:

<google-image-search callback="onImageSelect(image)" />

Directive Template

<a data-ng-click="callback({image: url})"></a>
Shiau answered 15/7, 2015 at 20:29 Comment(0)
W
2

Simply use:

<google-image-search callback="onImageSelect(image)" />

This example from AngularJS developer guide is pretty similar to your case: http://plnkr.co/edit/hYBxk070sgw54RElyWNq?p=preview

Walkup answered 16/7, 2015 at 2:47 Comment(0)
B
2

Following code is tested and working..

Directive call in html

<taxcode-picker call-back-fun="calculate_tax(a, b)"></taxcode-picker>

Sample Directive code

{
scope:'&',
link: function (scope, element, attrs) {
 scope.tax = {amount:12, rate:10.50};
 scope.obj = {number:12, value:10};

  scope.call_back = function (tax) {
    scope.callBackFun({a:tax, b:obj});
  }
}

}

Sample Controller

app.controller("sample", function($scope){
$scope.calculate_tax = function (tax, obj) {

        console.log("tax "+JSON.stringify(tax));

        console.log("obj "+JSON.stringify(obj));
    }
});
Belostok answered 6/12, 2018 at 10:48 Comment(0)
B
-6

try to change the scope object to be like this

scope: {
        callback: '='
    }

and it will work

Befog answered 15/7, 2015 at 21:0 Comment(1)
why all the down votes? I tried this and it WORKS! thanks, Ahmed. It is perfectly legit to pass a function via '='Calcifuge

© 2022 - 2024 — McMap. All rights reserved.