0

I'm new to AngularJS and I'm facing an issue with two way binding using AngularJS components. I have nested components and I'm trying to bind something and change it at the lower level (child component).

  1. It can only be changed from the parent level.
  2. $onChanges doesn't seem to work and I can't figure out why.

var myApp = angular.module('myApp', []);
myApp.controller('cc', function($scope) {
  $scope.text = 'Initial';
  $scope.data = {
    text: 'Initial'
  };
  $scope.change = function() {
    $scope.data.text = 'Root changed';
    $scope.text = 'Root changed';
  };
});

myApp.component('parent', {
  transclude: true,
  bindings: {
    data: "<",
    text: "="
  },
  template: '<div><button ng-click="parentController.click()">Parent change</button><div ng-transclude></div></div>',
  controller: function($scope) {
    var self = this;
    this.click = function() {
      self.data.text = 'Parent changed';
      self.text = 'Parent changed';
    };
    this.$onChanges = function() {
    	console.log('$onChanges');
    }
  },
  controllerAs: 'parentController'
});

myApp.component('child', {
  bindings: {
    data: "<",
    text: "="
  },
  template: '<button ng-click="childController.click()">Child Change</button>',
  controller: function() {
    var self = this;
    this.click = function() {
      self.data.text = 'Child changed';
      self.text = 'Child changed';
    };
  }, 
  controllerAs: 'childController'
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="cc">
  <div>
    {{data.text}} text
  </div>
  <div>
    {{text}} text
  </div>
  <button ng-click='change()'>
    Root Change
  </button>
  <parent data="data" text="text">
    <child data="data" text="text"></child>
  </parent>
</div>

Thanks!

JSFiddle demo

1
  • you want to change text from child right? Commented Sep 5, 2017 at 10:41

1 Answer 1

1

Actually with self.text you are only updating the own controller value and not the parent scope

The value in date is updating because object is passed by reference and where ever you change its value it will be reflected to the parent but the text value will not update like this

You need to specify which text property is now passed to child, becuase parent controller also has a text property, so if you want to pass the parents.parents text property do it like this in you <child>

<child data="data" text="$parent.$parent.text"></child>

I hope this will solve the issue

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.