Change variable in parent and child Angular controllers
by Tarek Faham
HTML
<div ng-app ng-controller="ParentCtrl as pc">
Name in Parent: <input id="name" type="text" ng-model="pc.nameModel"><br>
<input type="button" ng-click="pc.changeName()" value="change in parent">
<div ng-controller="ChildCtrl as cc">
Name in Chiled: <input id="name" type="text" ng-model="pc.nameModel">
<pre>{{cc.parentCities | json}}</pre>
<pre>{{cc.parentCitiesByScope | json }}</pre>
<pre>{{pc.cities | json}}</pre>
<input type="button" ng-click="cc.changeName()" value="change in child">
</div>
</div>
JavaScript
function ParentCtrl() {
var vm = this;
this.cities = ["NY", "Amsterdam", "Barcelona"];
this.nameModel = "init in parent";
this.changeName = function () {
this.nameModel = "Changed in parent";
}
}
function ChildCtrl($scope) {
var vm = this;
//ParentCtrl.apply(vm, arguments);
this.changeName = function () {
$scope.pc.nameModel = "Changed in child";
}
vm.parentCitiesByScope = $scope.pc.cities;
vm.parentCities = vm.cities;
}