【问题标题】:Angularjs. Inheritance scope in nested directive角。嵌套指令中的继承范围
【发布时间】:2016-04-05 18:50:01
【问题描述】:

目前,尝试以 Angular2 风格编写代码,即不使用控制器。面临从外部和内部指令的数据传输问题。如何正确执行? 主要问题是内部指令如何访问外部作用域并使用内部指令模板中的数据?例子 on codepen

<test-directive>
  <nested/>
</test-directive>

【问题讨论】:

    标签: javascript angularjs scope angular angular-directive


    【解决方案1】:

    我已经简化了你的 codepen,请参阅我修改后的 version

    class Nested {
      restrict='E';  
      template='<p>Nested {{inner.outer}} {{inner.last}}</p>';
      controller=function(){
        this.last='Pupkin';
      };
      controllerAs='inner';
      bindToController={
        outer: '=' // a communicating point of outer and inner directives
      };
    }
    

    重点是,在bindToController 中,您可以在此处添加端点变量,如outer。在外部模板中,给它一个类似的值:&lt;nested outer="outer.first"/&gt;

    @Günter Zöchbauer 的答案是针对 Angular 2。

    另外,如果您想查看使用 Angular 1 的组件样式的完整示例,您可以查看我的express-angular-es6-starter,使用 ES6 和组件样式 Angular 1 的 todo mvc 代码。

    【讨论】:

    • 谢谢!我知道这样的事情,但我认为这很耗时,还是我错了?
    • 你能解释一下什么时候使用bindsToController吗?因为我在每个指令中都写了,对吗?我注意到您将它用作对象,并且我认为 this 的变量是布尔值...
    • 是否可以借助 ng-transclude 连接过去和未来?例如,访问桨中“max”和“min”滑块的值?像这样 --> template
    • @powerman23rus 这里是一个很好的article for bindToController,它可以是布尔值或对象。
    【解决方案2】:

    你需要明确地传递值

    <test-directive>
      <nested [someInput]="somePropertyOnParent"></nested>
    </test-directive>
    
    @Component({
      selector: 'nested',
      template: `<ng-content></ng-content>`)}
    class Nested {
      @Input() someInput;
    
      ngOnInit() {
        console.log(this.someInput);
      }
    }
    

    【讨论】:

    • 这个解决方案是Angulyar 2,但我必须做同样的事情,只使用Angular1!不过还是谢谢)
    猜你喜欢
    • 2013-10-07
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多