Friday, July 1, 2016

pass data from one controller to another controller using $rootScope in angularjs

<html>
<head>
    <script src="Scripts/angular.min.js"></script>
</head>
<body>
    <script>
        var app = angular.module('MyApp', []);
        app.controller('ParentCtrl',
        function ParentCtrl($scope, $rootScope) {
            $scope.Parents = "Parent Controller";
            $scope.go = function () {
                $rootScope.$broadcast('parent', $scope.Parents)
            }
        });
        app.controller('SiblingCtrl',
        function SiblingCtrl($scope, $rootScope) {
            $scope.Childs = "Child Controller";
            $rootScope.$on('parent', function (event, data) {
                alert(data);
                $scope.transdata = data + " parent";
            });
        });

    </script>
    <div ng-app="MyApp">
        <div ng-controller="ParentCtrl">
            {{Parents}}
            <button ng-click="go()">Button </button>
            <div ng-controller="SiblingCtrl">
                {{Childs}}
                {{transdata}}
            </div>
        </div>
    </div>
</body>
</html>


No comments:

Post a Comment