如何在我的 angular 指令中使用注册的控制器? [英] How can I use a registered controller in my angular directive?

查看:14
本文介绍了如何在我的 angular 指令中使用注册的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样注册的控制器:

I have a controller registered like this:

myModule.controller('MyController', function ($scope, ...some dependencies...)
{
    ....

在 HTML 中使用 ng-controller="MyController" 一切正常,但现在我想将此控制器用作指令的控制器.类似这样的事情:

Using ng-controller="MyController" in the HTML it all works fine, but now I want to use this controller as my directive's controller. Some thing like this:

otherModule.directive('myDirective', function() {
    return {
        restrict: 'A',
        replace: true,
        controller: ??????????,
        scope: {
            foo: '=',
            blah: '=',
        },
        template: '....'
    }
});

我已经厌倦了放置 MyController 但它错误地显示MyController 未定义".我敢肯定,如果我只是将 MyController 放在全局命名空间中,它会正常工作,但我不想要全局命名空间中的任何内容.如果它有所不同,myModule 被定义为 otherModule 的依赖项.如何获得对这个控制器的引用以供我的指令使用?

I tired just putting MyController but it errors out saying "MyController is not defined". I'm sure if I just put MyController in the global namespace, it would work fine, but I don't want anything in the global namespace. If it makes a difference, myModule is defined as a dependency for otherModule. How can I get a reference to this controller for my directive to use?

按照建议,我尝试了 $controller('MyController'),但现在出现以下错误:

As suggested, I tried $controller('MyController'), but now I am getting the following error:

Error: Unknown provider: $scopeProvider <- $scope <- myDirectiveDirective
at Error (<anonymous>)
at http://localhost/resources/angular.js?_=1360613988651:2627:15
at Object.getService [as get] (http://localhost/resources/angular.js?_=1360613988651:2755:39)
at http://localhost/resources/angular.js?_=1360613988651:2632:45
at getService (http://localhost/resources/angular.js?_=1360613988651:2755:39)
at invoke (http://localhost/resources/angular.js?_=1360613988651:2773:13)
at Object.instantiate (http://localhost/resources/angular.js?_=1360613988651:2805:23)
at http://localhost/resources/angular.js?_=1360613988651:4621:24
at otherModule.directive.restrict (http://localhost/resources/app.js?_=1360613988824:862:15)
at Object.invoke (http://localhost/resources/angular.js?_=1360613988651:2786:25) 

我不知道如何处理这个错误.是否需要更多的东西来完成这项工作?

I'm not sure what to make of this error. Is there more needed to make this work?

推荐答案

看来你可以直接使用:

controller: 'MyController' 

如果控制器与指令在同一个模块中,或者由包含指令的模块组成的更高级别的模块.

IF the controller is in the same module as the directive or a higher level module composed of the module with the directive in it.

当我尝试将两个不同的模块组合成一个应用程序模块(一个用于控制器,一个用于指令)时,这不起作用.

When I tried it with two different modules composed into an app module (one for the controller and one for the directive), that did not work.

这篇关于如何在我的 angular 指令中使用注册的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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