4lackof
4lackof

Reputation: 1390

Pass data from child component to parent and back down

Say I have a component that looks like this:

parent.component.js

...
template: `<div>
             <child-one value="value" callback="callback"></child-one>
             <child-two value="value"></child-two>
           </div>`,
controller: function() {
  this.callback = function(n) {
    this.value = n;
  }
}
...

Then the child components look like this:

childOne.component.js

...
bindings: {
  value: '<',
  callback: '<'
},
template: `<input type="text"
                  ng-model="$ctrl.value"
                  ng-change="$ctrl.callback($ctrl.value)"
           />`
...

childTwo.component.js

...
bindings: {
  value: '<'
},
template: `<div>{{$ctrl.value}}</div>`
...

(binding technique thanks to krawaller)

I want the value that is set in childOne to go to childTwo. Updating the value in childOne does update the value in the parent but does not pass it down to childTwo.

Upvotes: 1

Views: 4807

Answers (1)

Vaibhav Shitole
Vaibhav Shitole

Reputation: 79

Note: You are setting values in the this object. Not directly in the $scope.

Use $scope, instead of this

Modified code:

parent.component.js

...
template: `<div>
             <child-one value="value" callback="callback"></child-one>
             <child-two value="value"></child-two>
           </div>`,
controller: function($scope) {
  $scope.callback = function(n) {
    $scope.value = n;
    console.log($scope.value);
  }
}
...

If you want to write a code with this keyword, then use controllerAs syntax.

Refer below code for parent.component.js

...
template: `<div>parent: {{vm.value}} <br/><div/>
         <div>
            <child-one value="vm.value" callback="vm.callback"></child-one>
            <child-two value="vm.value"></child-two>
         </div>`,
controller: function() {
  const vm = this;
  vm.callback = function(n) {
    vm.value = n;
    console.log(vm.value);

  }
},
controllerAs: "vm"
...

Result: Updating the value in childOne will update the value in the parent as well as childTwo.

Upvotes: 1

Related Questions