Understanding Angular’s $scope event system with $broadcast and $on
$broadcast — dispatches the event downwards to all child scopes,
$emit — dispatches the event upwards through the scope hierarchy.
<html>
<head>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module('sathya', []);
app.controller('ParentCtrl',
function ParentCtrl($scope) {
$scope.g = "Parent Controller";
$scope.go = function () {
$scope.$broadcast('parent', $scope.g)
}
});
app.controller('SiblingCtrl',
function SiblingCtrl($scope) {
$scope.g1 = "Child Controller";
$scope.$on('parent', function (event, data) {
$scope.h = data+" parent";
});
});
</script>
<div ng-app="sathya">
<div ng-controller="ParentCtrl">
{{g}}
<button ng-click="go()">Button </button>
<div ng-controller="SiblingCtrl">
{{g1}}
{{h}}
</div>
</div>
</div>
</body>
</html>
$broadcast — dispatches the event downwards to all child scopes,
$emit — dispatches the event upwards through the scope hierarchy.
<html>
<head>
<script src="Scripts/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module('sathya', []);
app.controller('ParentCtrl',
function ParentCtrl($scope) {
$scope.g = "Parent Controller";
$scope.go = function () {
$scope.$broadcast('parent', $scope.g)
}
});
app.controller('SiblingCtrl',
function SiblingCtrl($scope) {
$scope.g1 = "Child Controller";
$scope.$on('parent', function (event, data) {
$scope.h = data+" parent";
});
});
</script>
<div ng-app="sathya">
<div ng-controller="ParentCtrl">
{{g}}
<button ng-click="go()">Button </button>
<div ng-controller="SiblingCtrl">
{{g1}}
{{h}}
</div>
</div>
</div>
</body>
</html>
No comments:
Post a Comment