Pass callback function to directive

别来无恙 提交于 2019-11-28 07:34:52

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>

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

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));
    }
});

Many AngularJs developers have already know about AngularJs Directives and probably know about directive scope and it's methods.

As you know, there are 3 AngularJs Directive scope methods: '@', '=', '&', but now we are going to talk about only '&' method.We are going to see, how we can implement method '&' in our applications.

When we define any function inside current scope and want to implement it to any directives,Remember one thing: you have to pay attention on your function's arguments and their order.If you want more here is a great article about it:

http://www.w3docs.com/snippets/angularjs/angularjs-directive-scope-method.html

try to change the scope object to be like this

scope: {
        callback: '='
    }

and it will work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!