1

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.

4lackof
  • 1,250
  • 14
  • 33

1 Answers1

1

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.

  • Okay so then when are you supposed to use `$scope` over `this`? From what I've found/learened, with `components` you use `this` as it creates an `isolated-scope`, unless you want to access `$watch`, `$digest`, `$emit` (at least per https://teamtreehouse.com/community/angularjs-controller-thismodel-vs-scopemodel) – 4lackof Jun 21 '18 at 18:41
  • For using $scope over this [refer link](https://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers) Also, as per my point of view, "this" [Controller Ref] is also a variable which will be assign to $scope in the HTML. You can have a look into the $scope parameter in details. You will get to know that "this" [controller ref] is assigned in the scope of that HTML itself. So, no matter when to use $scope or this. Just follow the conventions. Thanks. – Vaibhav Shitole Jun 22 '18 at 04:54