使用参数执行范围绑定函数 [英] Executing a scope bound function with parameters

查看:21
本文介绍了使用参数执行范围绑定函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在指令中有这样的函数:

If I have a function like this in a directive:

 scope: {
      loadChildren: "&"
 },

如何从我的控制器调用它并传递参数?

How can I call this from my controller and pass parameters?

$scope.loadChildren(param1, param2);

我的指令执行我传递给它的函数,但我没有看到任何参数.

My directive executes the function I pass it but I don't see any parameters.

有没有办法像这样传递它们?

Is there any way to pass them like this?

编辑回复:rodyhaddad 的回答

rodyhaddad 指明了方向,并给出了将参数传递给绑定函数的正确格式.但是,为了让它工作,我还必须像这样将参数键添加到我的 HTML 中:

rodyhaddad points the way and gives the correct format for passing parameters to a bound function. However, in order to get it working I also had to add the parameter keys into my HTML like this:

<example load-children="load(param1, param2)"></example>

然后在我的控制器上我可以看到参数:

Then on my controller I can see parameters:

$scope.load = function (param1, param2) {
    debugger;
};

推荐答案

当你这样做

  loadChildren: "&"

这是生成函数的代码(源代码)

This is the code that generates the function (source code)

case '&': {
  parentGet = $parse(attrs[attrName]);
  scope[scopeName] = function(locals) {
    return parentGet(parentScope, locals);
  };
  break;

如您所见,您传递给 loadChildren 的任何内容都将成为传递给 $parselocals.

So as you can see, whatever you pass to loadChildren will become the locals passed to $parse.

所以正确的调用方式是:

So the correct way to call it would be:

$scope.loadChildren({
  param1: param1,
  param2: param2
});

如果你想要另一个例子,这里是事件指令(如 ngClick)如何将 $event 暴露给它们的表达式:源代码

If you want another example, here's how event directives (like ngClick) expose $event to their expressions: source code

这篇关于使用参数执行范围绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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