在 Angular 指令中使用 require 的 bindToController [英] bindToController with require in Angular Directive

查看:36
本文介绍了在 Angular 指令中使用 require 的 bindToController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If my directive uses "require" to use a different directive, say ngModel, and uses isolate scope how am I able to use the bindToController syntax and still be able to access the injectables (ngModelController) from the controller?

推荐答案

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

How would you do this without bindToController? All that bindToController: true does is it binds the isolate scope property scope: { prop: "=" } to the property of the controller: this.prop.

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

In both cases, the way to pass a "required" controller would be the same, which is to require your own controller and set its property to whatever you want, including other controllers:

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;
    }
  }
});

这篇关于在 Angular 指令中使用 require 的 bindToController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆