【问题标题】:Angular directives Controller not found by require要求未找到角度指令控制器
【发布时间】:2015-07-07 03:46:01
【问题描述】:

这就是问题所在,我正在尝试通过使用指令来拆分我的 html 以呈现子标题。

在子标题中,我正在做一些逻辑来呈现一些按钮。用于此的所有逻辑都编码在此视图的控制器中。

所以我写了一个指令来为我的子标题创建一个元素:

 angular.module('myApp')
  .directive('subHeader', ['ServiceOne','ServiceTwo',
  function(ServiceOne, ServiceTwo){
    return{
      restrict: 'E',
      require: '^MyCtrl',
      link: function(scope, element, attrs, ctrl){
          console.log(ctrl);

         // Logic for buttons in sub header

      },
      templateUrl: '--here my path to the .html template--'
    };
  }]);

html 模板在视图中渲染得很好,所以我尝试在链接方法中移动我的子标题中存在的逻辑函数。但我无法记录现有的控制器。

我只想补充一点,我需要控制器,因为子标题中的逻辑取决于该控制器检索的数据。

我错过了什么或我做错了什么?

【问题讨论】:

  • 什么是MyCtrl。它应该是 html 树中父指令的控制器。
  • 这个视图的控制器 - 你的意思是页面上的某个地方你有ng-controller="MyCtrl" 还是指令有它自己的控制器?

标签: javascript angularjs angularjs-directive


【解决方案1】:

在指令中,我们使用“controller”和“controllerAs”而不是“require”。 “controller” - 控制器的实际名称(字符串或控制器函数本身)。 "controllerAs" - 可以在 html 视图中使用的控制器的别名

 angular.module('myApp')
  .directive('subHeader', ['ServiceOne','ServiceTwo',
   function(ServiceOne, ServiceTwo){
    return{
      restrict: 'E',
      controller: 'MyCtrl',
      link: function(scope, element, attrs, ctrl){
        console.log(ctrl);

        // Logic for buttons in sub header

       },
       templateUrl: '--here my path to the .html template--'
    };
 }]);

 angular.module('myApp').controller("MyCtrl", function($scope){
    //Do your stuff
 });

angular.module('myApp')
  .directive('subHeader', ['ServiceOne','ServiceTwo',
   function(ServiceOne, ServiceTwo){
    return{
      restrict: 'E',
      controller: function($scope)(){
       // Do your stuff
      },
      controllerAs: 'MyCtrl',
      link: function(scope, element, attrs, ctrl){
        console.log(ctrl);

        // Logic for buttons in sub header

       },
       templateUrl: '--here my path to the .html template--'
    };
 }]);

【讨论】:

  • @Yashika Garg,谢谢你,我现在可以登录我的控制器了。但我仍然对如何在指令中使用 --require -- 感到困惑。
  • 我希望这可以帮助你stackoverflow.com/questions/15672709/…
猜你喜欢
  • 2015-01-29
  • 1970-01-01
  • 2016-08-06
  • 2016-03-11
  • 2015-02-11
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2016-06-08
相关资源
最近更新 更多