用'require'链接到封闭指令控制器的指令

时间:2017-03-11 17:33:07

标签: angularjs angularjs-directive

我正试图在angularjs指令中获得一个封闭的控制器。我还需要一个ngModel,这应该像

一样
.directive("myFunnyDirective", function(....) {
    return {
        require: ["ngModel", "?^myFunnyCtrl"],
        scope: {},
        ...
    }
}

但是找不到我的控制器。我很确定这是因为我在查找NgModelController时违反了命名约定,我需要写ngModel。所以我改名了,但仍然有问题。由于调试魔法很难,我想知道,如果规则确实是require: "?^abcXyz"寻找封闭的AbcXyzController或者它是如何工作的?或者是问题之间的孤立范围?

1 个答案:

答案 0 :(得分:2)

您必须要求使用封闭指令(它基本上为您提供此指令的控制器)。

var myFunnyApp = angular.module('myFunnyApp', []);

myFunnyApp.directive("myFunnyDirective", function() {
  return {
    template: '<my-funnier-directive></my-funnier-directive>',
    controller: function() {
      this.getJoke = function() {
        return 'Knock, knock. ...'
      }
    }
  }
});

myFunnyApp.directive("myFunnierDirective", function() {
  return {
    require: '?^myFunnyDirective',
    scope: {},
    template: 'Tell a joke! - {{joke}}',
    link: function(scope, element, attrs, myFunnyDirectiveCtrl) {
      scope.joke = myFunnyDirectiveCtrl.getJoke();
    }
  }
});
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>

<body>
  <div ng-app="myFunnyApp">
    <my-funny-directive></my-funny-directive>
  </div>
</body>

</html>