I created this sample page which has two controllers and I am experimenting how I can use two-way binding so that when the h3
heading in anotherController is updated once a user enters their age. I am not sure how to wire the controllers once the age is updated. I am looking the event flow to be Update ageHolder.age -> Update AgeData -> Update anotherController getCategory expression.
With these two controllers, I was able to trigger ageUpdated
event but I could not get how to update the text in h3
.
<!DOCTYPE html>
<html ng-app="factoryApp">
<head>
<meta charset="utf-8" />
<script src="/scripts/angular.js"></script>
<script src="/scripts/FactoryApp.js"></script>
</head>
<body>
<div ng-controller="factoryController as gsc">
<label>Age:<input type="text" ng-model="gsc.ageHolder.age" ng-model-options="{ getterSetter: true }"/></label>
</div>
<div ng-controller="anotherController as asc">
<h3>You are {{ asc.getCategory() }}.</h3>
</div>
</body>
</html>
var app = angular.module('factoryApp', []);
app.factory('AgeData', function () {
return {age: 0};
});
app.controller('factoryController', function(AgeData){
var gsc = this, _age = 20;
gsc.ageHolder = {};
gsc.ageHolder.age = function (anAge) {
if (arguments.length) {
AgeData.age = anAge;
AgeData.sendMessage(anAge);
}
};
});
app.controller('anotherController', function(AgeData, $scope) {
console.log('Age is ', AgeData);
var asc = this;
var age = AgeData.age;
$scope.$on('ageUpdated', function() {
console.log('Age is updated');
age = AgeData.age;
});
asc.getCategory = function() {
if (age < 5)
return "Toddler";
else if (age < 13)
return "Child";
else if (age < 20)
return "Teen";
else if (age < 30)
return "Youngster";
else if (age < 45)
return "Middle age";
else if (age < 60)
return "Mature person"
else
return "Senior Person";
}
});