Access methods through a parent component in a child with Angular 1

0

Hello, I'm having a lot of trouble getting information between 2 components working with Angular 1. This is my example:

angular.module("parent",["child"]).component("parent",{
  template : "<p> <child name></child> </div>",
  controllerAs:"parent",
  controller : {
    constructor(){}
  }
});

angular.module("child",[]).component("child",{
  binding : {
    "name" = "="
  }
  template : "<span>{{name}}</span>",
  controllerAs : "child",
  controller : {
    constructor(){
      this.name = name;
    }
  }
});

So far, if I manually enter the value at <child name="foo"></child> the child component has its content changed. The problem is that I'm not understanding how parent I'll be able to change the contents of the child

Could anyone explain?

    
asked by anonymous 26.12.2016 / 18:57

1 answer

1

What you can do is simply pass a property of the parent component to the name attribute. Then, by changing the value of this property in the parent component, the binding process of AngularJs will be responsible for propagating the change to the child component.

  

You are using the binding = modifier, which means that the name property can be modified in both parent and child components.

Example:

angular.module('parent', ['child']).component('parent', {
  template: 'parent: {{ parent.myName }} <br> child: <child name="parent.myName"></child>',
  controllerAs: 'parent',
  controller: function() {
    this.myName = 'foo';
  }
});

angular.module('child', []).component('child', {
  bindings: {
    name: '<'
  },
  template: '<span>{{ child.name }}</span>',
  controllerAs: 'child',
  controller: function() {
    this.name = 'bar';
  }
});

angular.element(function() {
  angular.bootstrap(document, ['parent']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<parent></parent>
    
27.12.2016 / 11:58