在同一指令的链接功能内使用指令控制器中的功能 [英] Using functions from directive controller within link function of same directive

查看:67
本文介绍了在同一指令的链接功能内使用指令控制器中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我对指令控制器的工作方式有一个基本的误解,据我了解,它们被用作暴露给其他指令的一种API.控制器.我正在尝试使控制器和链接功能在内部进行通信.

Perhaps I have a fundamental misunderstanding of how directive controllers work, from what I understand they are used as a sort of API to be exposed to other directives & controllers. I am trying to get the controller and link function to communicate internally.

例如,我希望能够通过控制器功能设置一个变量,然后在链接功能中使用它:

For example I would like to be able to set a variable via the controller function and then use it in the link function:

var app = angular.module('test-app', []);

app.directive('coolDirective', function () {
    return {
        controller: function () {
            this.sayHi = function($scope, $element, $attrs) {
                $scope.myVar = "yo"
            }
        },
        link: function(scope, el, attrs) {
            console.log(scope.myVar);
        }   
    }
});

如何在链接功能中访问myVar或sayHi?还是我完全错过了重点?

How can I access myVar or sayHi within the link function? Or have I just missed the point completely?

推荐答案

控制器的$ scope(在控制器中定义,而不是在sayHi函数中定义)和链接scope相同.可以从链接中使用在控制器中设置的内容,反之亦然.

Both controller's $scope (defined in the controller, not in the sayHi function) and link scope are the same. Setting something in the controller will be usable from the link or viceversa.

您遇到的问题是sayHi是一个永远不会触发的函数,因此永远不会设置myVar.

The problem you have is that sayHi is a function that is never fired so myVar is never set.

由于sayHi不在范围内,因此您需要引用控制器并执行此操作,您可以添加第四个参数,如下所示:

Since sayHi is not in the scope, you need a reference to the controller and to do it, you can add a fourth parameter like this:

link: function(scope, element, attr, ctrl) {}

然后您可以执行ctrl.sayHi()(但同样,sayHi的那些参数属于控制器功能.)

Then you could do a ctrl.sayHi() (But again, those params of sayHi belongs to the controller function.)

如果您需要另一个控制器,但仍想使用其自己的指令,那么您也将需要它.因此,如果此coolDirective需要访问notCoolAtAll的控制器,则可以执行以下操作:

If you ever need to require another controller and still wanting to use its own directive, then you will need to require it too. So if this coolDirective needs to access to the controller of notCoolAtAll you could do:

require: ['coolDirective', 'notCoolAtAll']

可以解决问题. link函数将接收一个控制器数组作为第四个参数,在这种情况下,第一个元素是coolDirective ctrl,第二个元素是notCoolAtAll一个.

That will do the trick. The link function will receive then an array of controllers as the fourth param and in this case the first element will be coolDirective ctrl and the second one the notCoolAtAll one.

这是一个小例子: http://plnkr.co/edit/JXahWE43H3biouygmnOX?p=预览

这篇关于在同一指令的链接功能内使用指令控制器中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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