I do this in Ionic Framework. It started in the home.html
template with eventmenu.home
state. The $scope.aaa
variable is 10
and it shows that value correctly. However, in a child controller TestCtrl
of that template, I cannot change the $scope.aaa
value and gets it updated. What's wrong with my method as why aaa
did not get increased? Is TestCtrl
in a different scope than HomeCtrl
although it should be the child of HomeCtrl
, no?
CODE:
http://codepen.io/hawkphil/pen/xbmZGm
HTML:
<script id="templates/home.html" type="text/ng-template">
<ion-view view-title="Welcome" >
<ion-content class="padding" >
<p>Swipe to the right to reveal the left menu.</p>
<p>(On desktop click and drag from left to right)</p>
<p>{{ aaa }}</p>
<div ng-controller="TestCtrl">
<a ng-click="clickMe()" href="">Click Me</a>
</div>
</ion-content>
</ion-view>
</script>
JS:
.controller('HomeCtrl', function($scope) {
$scope.aaa = 10;
})
.controller('TestCtrl', function($scope) {
$scope.clickMe = function() {
$scope.aaa++;
}
})
p.s I am using the code from somebody so please ignore other stuffs.
This isn't an issue with Ionic, or with ui-router, or really even with Angular. It's just how javascript works.
You can see the same issues arise in plain Angular using ng-if
. It has to do with how javascript inheritance works.
If the child scope doesn't have it's own aaa
property it uses it's parent. But once you click the button, you make it's own property, one more than the parent's was. But now they are separate properties, the parent's aaa
and the child's aaa
.
You can see a pure javascript example here...
Example. Click the Inc Parent
as much as you like, both the parent and child displays are incremented. Clicking the Inc Child
breaks the connection. Once the connection is broken you can "unhide" the parent value by deleting the child's property by clicking the Unhide
button.
code
var obj = function () {}
obj.aaa = 10
obj.inc = function () {
this.aaa += 1;
};
var objB = function () {};
objB.__proto__ = obj; // Make objB a child of obj
objB.inc = function () {
this.aaa += 1;
};
objB.unhide = function () {
delete this.aaa;
};
var update = function () {
document.getElementById("p").textContent = obj.aaa;
document.getElementById("c").textContent = objB.aaa;
};
update();
html
<button onclick="obj.inc(); update();">Inc Parent</button>
<button onclick="objB.inc(); update();">Inc Child</button>
<button onclick="objB.unhide(); update();">Unhide</button>
<p>
Parent's value: <span id="p"></p>
</p>
<p>
Child's value: <span id="c"></p>
</p>
Every controller has its own $scope
object. Child controllers can access their parents using $parent
:
.controller('TestCtrl', function($scope) {
$scope.clickMe = function() {
$scope.$parent.aaa++;
}
})