我们可以将两个控制器链接到一个自定义指令 [英] Can we link two controllers to a single custom directive

查看:56
本文介绍了我们可以将两个控制器链接到一个自定义指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我试图找到多个控制器与单个自定义指令的链接,但没有解决方案。这有可能实现与否。任何人都可以告诉我。

Hi All,
I tried to find linking of multiple controllers to a single custom directive, but no solution. Is this possible to achieve or not. Can anybody please tell me.

推荐答案

当您向HTML添加指令时,它会创建该指令的实例。根据您的配置方式,范围是他们与父控制器共享的唯一内容。如果需要在控制器/指令之间共享信息,请尝试创建共享信息的工厂。工厂是一个单例,允许您将信息/功能传递给任何调用工厂的人。
When you add a directive to the HTML it creates an instance of that directive. Depending on how you have configured it, the scope is the only thing they will share with the parent controller. If you need to share information between controllers / directives try creating a factory of the shared information instead. The factory is a singleton that will allow you to pass information / functionality around to whomever invokes the factory.


如果在作用域上定义了该函数,您应该可以通过指令的范围,除非它不是共享范围。然后你可以做的就是把它连接到控制器上,如下所示:



if the function is defined on the scope, you should be able to call it through the scope on the directive, unless it's not a shared scope. Then what you can do is attach it to the controller like so:

app.controller( 'myController', function( ) { 
    var me = this;
    me.myFunc = function ( ) { console.log ( ' hello world ' ) ; };
} )
. directive( 'myDirective', function ( ) {
    return {
        scope: { myVar : true },         // <- This creates isolated scope. If this is not defined, then it's a shared scope
        controller : '^myController',  // Tell Angular you need this controller.    Required. 
        // some other stuff for directive
        link : function (


scope,element ,attribute,ctrl){
ctrl.myFunc(); // 你可以访问所有控制器的功能
}
}
});
scope, element, attribute, ctrl ) { ctrl.myFunc ( ) ; // you have access here to all controller's functions } } } ) ;



让我知道这是否有帮助。


Let me know if this helps.


这篇关于我们可以将两个控制器链接到一个自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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