<!DOCTYPE html>
<html ng-app="sharing">
<head>
<script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl as vm">
<h1>Sharing data between parent and child controller</h1>
<p>The user name (Henri) is defined in the parent controller but displayed by the child controller.</p>
Hello {{$parent.user.name}} (using $parent in HTML code)
<br/> Hello {{parentUser.name}} (using $parent in child controller)
<br/> Hello {{user.name}} (using controller inheritance)
<br/>
<h1>Sharing data between unrelated controllers</h1>
<p>Using a factory to hold the common data.</p>
<h2>First controller</h2>
<button ng-click="increment()">+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2 as vm">
<h2>Second controller</h2>
<button ng-click="increment()">+</button>{{Holder.value}}
</div>
<p>Using events ($broadcast).</p>
<div ng-controller="ChildCtrl3 as vm">
<h2>First controller</h2> User name:
<input type="text" size="10" ng-model="name">
<button ng-click="sync()">Sync with emit</button>
<button ng-click="sync2()">Sync with broadcast</button>
</div>
<div ng-controller="ChildCtrl4 as vm">
<h2>Second controller</h2> Hello {{name}}
</div>
</div>
</body>
</html>
// Code goes here
var app = angular.module('sharing', []);
app.controller('ParentCtrl', function($scope) {
$scope.user = {
name: "Henri"
};
});
app.factory('Holder', function() {
return {
value: 0
};
});
app.controller('ChildCtrl', function($scope, Holder) {
$scope.parentUser = $scope.$parent.user;
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
app.controller('ChildCtrl3', function($scope, $rootScope) {
$scope.name = "World";
$scope.sync = function() {
$rootScope.$emit("namechanged", $scope.name);
};
$scope.sync2 = function() {
$rootScope.$broadcast("namechanged2", $scope.name);
};
});
app.controller('ChildCtrl4', function($scope, $rootScope) {
$scope.name = "World";
var destroyHandler = $rootScope.$on("namechanged", function(event, name) {
$scope.name = name;
});
$scope.$on('$destroy', destroyHandler);
$scope.$on("namechanged2", function(event, name) {
$scope.name = name;
});
});