将回调函数传递给指令 [英] Pass callback function to directive

查看:26
本文介绍了将回调函数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将回调函数从控制器传递给指令.

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

回调函数代码如下:

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

指令用法:

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

指令代码:

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

模板中的回调用法:

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

推荐答案

在从指令中调用表达式方法时,您需要以 JSON 格式从指令中传递参数,还应该更正您的指令 callback 属性值传递函数,如 callback="onImageSelect(image)"

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)"

指令用法:

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

指令模板

<a data-ng-click="callback({image: url})"></a>

这篇关于将回调函数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆