简体   繁体   English

AngularJS需要指令中的控制器

[英]Angularjs require controller from directive

I'm trying to create a directive that will be used in multiple places in the app and I want it to opt into a controller. 我正在尝试创建一个指令,该指令将在应用程序的多个位置使用,并且希望它选择加入控制器。

When using the controller method 使用控制器方式时

return {
      ...
      controller: 'BlogDashCourseCtrl',
      ...
      }

it gets the controller fine. 它可以使控制器正常运行。 But when I require it 但是当我需要的时候

return {
      ...
      require: '^BlogDashCourseCtrl',
      ...
      link: function($scope, iElm, iAttrs) {
          $scope.title = iAttrs.title; // Do not share me with other directives
          if($scope.title === $scope.step) { // $scope.step comes from a shared scope
              ...
          }
      }
}

it can't find the controller. 它找不到控制器。

I don't want the controller to be called multiple times. 我不想多次调用控制器。 I just want the directives to share a scope, have a private scope, too (so $scope in the directive doesn't bubble up) and do some stuff with a service. 我只希望指令共享一个作用域,也有一个私有作用域(因此指令中的$ scope不会冒泡),并使用服务做一些事情。

A directive is attached to a DOM node. 指令附加到DOM节点。 A DOM node can't have two scopes. DOM节点不能有两个范围。 Either you share the parent scope or you create an isolated one and explicitly inherit stuff from it. 您可以共享父作用域,也可以创建一个隔离的作用域并从中明确继承东西。

BlogDashCourseCtrl:
    this.step = 'whatever'; //maybe $scope.step


SomeDirective:
return {
      ...
      require: '^BlogDashCourseCtrl',
      ...
      link: function($scope, iElm, iAttrs, blogDashCourseCtrl) {
          $scope.title = iAttrs.title; // Do not share me with other directives
          if($scope.title === blogDashCourseCtrl.step) { // $scope.step comes from a shared scope
              ...
          }
      }
}

Notice that blogDashCourseCtrl does not reference the $scope of that directive/controller, but the reference itself. 注意, blogDashCourseCtrl并不引用该指令/控制器的$scope ,而是引用自身。 There really is extensive documentation on this, with examples. 确实有关于此的大量文档以及示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM