简体   繁体   English

如何从带有参数的指令调用角度控制器范围函数?

[英]How to call angular controller scope function from directive with parameters?

this is slightly different to the other questions on stack in that, I need to call my controller's functions with parameters that exist exclusively in my directive. 这与堆栈上的其他问题略有不同,我需要使用仅在我的指令中存在的参数来调用我的控制器函数。

directive (markup): 指令(标记):

<div do-something="doSomething(x)"></div>

directive (js): 指令(js):

var directive = function () {
    return {
        restrict: 'EA',
        templateUrl: '/angular/node-for-detail.html',
        scope: {
            doSomething: '&'
        }
    }
};

markup inside directive: 标记内部指令:

<span ng-click="doSomething('im not resolving')"></span>

function inside controller: 控制器内的功能:

$scope.doSomething = function(myVar) { //myVar is null };

So the problem is, inside the directive param.abs resolved fine, but then, inside the called scope function the parameters are null! 所以问题是,在指令param.abs里面解决得很好,但是在调用范围函数里面,参数是null! What am I doing wrong? 我究竟做错了什么? How can I get the parameter to make it through? 我怎样才能获得参数来完成它?

You need to decide on a standard name for the parameter to the function that will be specified in the markup (in your example, you used x ). 您需要确定将在标记中指定的函数的参数的标准名称(在您的示例中,您使用了x )。 Then you can create a function in the directive's isolate scope that will call the doSomething() method like so: 然后你可以在指令的隔离范围中创建一个函数,它将调用doSomething()方法,如下所示:

directive link function: 指令链接功能:

$scope.runCallback = function (param) {
    $scope.doSomething({x: param});
}

Then just change your markup inside the directive to be: 然后只需将指令内的标记更改为:

<span ng-click="runCallback('im not resolving')"></span>

Now your markup call ( <div do-something="doSomething(x)"></div> ) and the function inside the controller will work correctly. 现在你的标记调用( <div do-something="doSomething(x)"></div> )和控制器内的函数将正常工作。

Try replace your markup inside directive be like this : 尝试在指令中替换你的标记,如下所示:

<span ng-click="doSomething()('im not resolving')"></span>

And directive markup : 和指令标记:

<div do-something="doSomething"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM