bindToController 在 Angular 指令中需要

bindToController with require in Angular Directive

如果我的指令使用“require”来使用不同的指令,比如 ngModel,并使用隔离范围,我如何才能使用 bindToController 语法并且仍然能够从控制器访问注射剂 (ngModelController)?

如果没有 bindToController,你会怎么做? bindToController: true 所做的就是将隔离范围 属性 scope: { prop: "=" } 绑定到控制器的 属性:this.prop.

在这两种情况下,传递 "required" 控制器的方式是相同的,即 require 您自己的控制器并将其 属性 设置为您想要的任何值,包括其他控制器:

app.directive("foo", function(){
  return {
    require: ["foo", "bar"],
    controller: function(){
      this.doSomethingWithBar = function(){
        this.bar.doSomething();
      };
    },
    controllerAs: "ctrl",
    bindToController: true,
    link: function(scope, element, attrs, ctrls){
      var foo = ctrls[0], bar = ctrls[1];
      foo.bar = bar;
    }
  }
});