Executing a scope bound function with parameters [duplicate]

烈酒焚心 提交于 2019-12-11 00:48:05

问题


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?

EDIT re: rodyhaddad's answer

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

回答1:


When you do

  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;

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

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



来源:https://stackoverflow.com/questions/18305247/executing-a-scope-bound-function-with-parameters

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