从链接函数内部带有参数的指令角度调用控制器方法

Angular calling controller method from directive with parameters inside link function

本文关键字:指令 调用 方法 控制器 参数 函数 链接 内部      更新时间:2023-09-26

我有一个指令,它有一个链接函数,类似于:

 scope: {
                target: '@',
                fooFunction: '&'
            },
link:
   scope.$apply(attrs.fooFunction);
var fooValue= scope.fooFunction(data,scope.target);

在我的控制器中,我将此功能定义为:

$scope.fooFunction= function (data, target) {
//some code here
}

当我在html中使用这个时,我会这样写:

<div some-directive  foo-Function="fooFunction(ctrl.data,'hardCoded')"  target="actualValue"></div>

其中我使用myController作为ctrl。

我的问题是,即使我将值作为scope.target传递,它也总是选择hardCoded值。有什么方法可以传递scope.target中的值而不是硬编码的值吗?

正如您提到的目标为@,因此您需要使用{{}}来评估该属性值,该值将被视为单向绑定。

就像你可以在控制器actualValue变量中有值,然后你可以像target="{{ctrl.actualValue}}" 一样绑定它

标记

<div some-directive 
  foo-function="fooFunction(ctrl.data,'hardCoded')"
  target="{{ctrl.actualValue}}">
</div>