1

I have an object in MainCtrl and pass it to child component with one-way binding. When I change it in child template, changed parent object in MainCtrl. Where is my problem?

(function(angular) {
  'use strict';
angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
  this.hero = {
    name: 'Spawn'
  };
});
})(window.angular);

(function(angular) {
  'use strict';
angular.module('heroApp').component('heroDetail', {
  templateUrl: 'heroDetail.html',
  bindings: {
    hero: '<'
  }
});
})(window.angular);
<div ng-controller="MainCtrl as ctrl">
  <span>Parent Obejct Name: </span>{{ ctrl.hero.name }}
  <br/>
  <hero-detail hero="ctrl.hero"></hero-detail>
</div>

<span>Child Object Name: {{$ctrl.hero.name}}</span>
<br/>
<input type="text" ng-model="$ctrl.hero.name" />

1 Answer 1

3

It's not your problem. Objects are always passed by reference. No matter, one-way or two-way binding are used. To avoid it, you must do copy of object in child component

Note however, that both parent and component scope reference the same object, so if you are changing object properties or array elements in the component, the parent will still reflect that change. The general rule should therefore be to never change an object or array property in the component scope

Understanding Components

One-way data-binding in Angular 1.5

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.