javascript - 如何将 Controller 添加到指令中?

标签 javascript angularjs angularjs-directive

我正在尝试在我的应用程序中创建一个指令。但是,我需要在不同的地方使用指令,并且它们有自己的 Controller 。

所以在我的指令中

directive('test', [function($popover) {
        return {
            restrict: 'E',
            scope: false,
            link: function(scope, elem, attrs) {

            }
        };
    }
])

如何将两个 Controller 添加到一个指令?

谢谢!

最佳答案

您可以使用namecontroller="@"选项。

.directive('test', [function($popover) {
        return {
            restrict: 'E',
            scope: false,
            controller : "@", 
            name:"controller",
            template:'<div>{{value}}</div>',
            link: function(scope, elem, attrs) {

            }
        };
    }

例如:-

  <test controller="ctrl1"></test>
   .....
  <test controller="ctrl2"></test>

当您指定 controller= '@' 时,Angular 将查找具有为 中提到的元素属性指定的属性值(您可以为该属性指定任何名称)的已注册 Controller 。名称选项。

<强> Plnkr

这是 Angular Directive(指令)实现的片段:-

         if (controllerDirectives) {
         ....

            controller = directive.controller;
            if (controller == '@') {
              controller = attrs[directive.name];
            }

            controllerInstance = $controller(controller, locals);

关于javascript - 如何将 Controller 添加到指令中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25556557/

相关文章:

javascript - 如何添加 $scope.$on 以在没有 Controller 的情况下查看

angularjs - Angular js 使用 $rootScope.emit 从 websocket 和 $http 服务传播 cummunicates

javascript - BreezeJs,saveChanges() - 未捕获的类型错误 : Cannot read property 'statusText' of undefined

javascript - 当我们点击动态创建的编辑图标时,如何更改输入字段中的值?

javascript - 已选中 ="checked"未在 Chrome 中呈现为选中的单选按钮

javascript - 来自 Controller 的 Angular 对象未在 html 中显示

javascript - 在 angularjs 指令中不起作用的标签

javascript - Angular : Variable template inside directive

javascript - 如何在Vue完全加载和初始化后才运行VueJS代码?

javascript - 模具 : Namespacing custom elements’ names to avoid collisions