Javascript 将回调函数传递给指令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31440366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass callback function to directive
提问by Mike
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.
我看过很多类似的问题,但不明白我错在哪里。
回答by Pankaj Parkar
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)"
从指令调用表达式方法时,您需要以JSON
格式传递指令中的参数,还应该更正指令callback
属性值以传递函数,例如 callback="onImageSelect(image)"
Directive usage:
指令用法:
<google-image-search callback="onImageSelect(image)" />
Directive Template
指令模板
<a data-ng-click="callback({image: url})"></a>
回答by Joy
Simply use:
只需使用:
<google-image-search callback="onImageSelect(image)" />
This example from AngularJS developer guideis pretty similar to your case: http://plnkr.co/edit/hYBxk070sgw54RElyWNq?p=preview
AngularJS 开发人员指南中的这个示例与您的案例非常相似:http: //plnkr.co/edit/hYBxk070sgw54RElyWNq?p=preview
回答by Dinesh Vaitage
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));
}
});
回答by Ahmed Eid
try to change the scope object to be like this
尝试将范围对象更改为这样
scope: {
callback: '='
}
and it will work
它会起作用