Search code examples
javascriptangularjsscopeangularangular-directive

Angularjs. Inheritance scope in nested directive


At the moment, trying to write code in a Angular2 style, i.e. without the use of controllers. Faced with the problem of data transfer from the external and internal directive. How to do it correctly? The main question is how the inside of the directive to access the external scope and use the data in the template of internal directives? Example on codepen

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

Solution

  • I've simplified you codepen, see my modified 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
      };
    }
    

    The point is that, in bindToController, you can add your endpoint variable, as outer here. And in the outer template, give it a value like: <nested outer="outer.first"/>.

    @Günter Zöchbauer's answer is for the Angular 2.

    Also, If you want to see a whole example of using component style with Angualr 1, you can see my express-angular-es6-starter, A todo mvc with ES6 and component style Angular 1 codes.