Monday 6 June 2016

Call a method in parent controller from the child controller in Angular

In this post we are going to see how to call a method which is present in the parent controller from the child controller.

HTML:
*******

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <title></title>
</head>
<body data-ng-app="locapp">

    <div ng-controller="parentController" class="well">
        <ul>
            <li ng-repeat="dt in data">{{dt}}</li>
        </ul>
        <div class="btn btn-info" ng-click="getData()">Call Child Controller Method</div>

        <div class="btn btn-info" ng-click="getStudent()">Call Sibling Controller   Method</div>
        <div ng-controller="childController">
            <ul>
                <li class="well-sm" ng-repeat="emp in employees">{{emp}}</li>
                <br/>
                <div class="btn btn-info" ng-click="getParentInfo()">Call Parent Controller Method</div>
            </ul>
        </div>
    </div>

    <div ng-controller="siblingController">
        <ul class="panel">
            <li class="well-sm" ng-repeat="stud in students">{{stud}}</li>
        </ul>
    </div>

<script type="application/javascript" src="js/jquery-2.0.0.min.js"></script>
<script type="application/javascript" src="js/bootstrap.min.js"></script>
<script type="application/javascript" src="js/angular.js"></script>
<script type="application/javascript" src="ang/issue.js"></script>

</body>

</html>

Js:
*****

From the Controller side


var locapp = angular.module('locapp', []);

locapp.controller('parentController'function ($scope, $rootScope) {
    var i = 0;
    $scope.data = [];

    $scope.getData = function () {
        i++;
        $scope.$broadcast('getEmployees', ['Name ' + i, 'ABCDG' + i]);
    };

    $scope.getStudent = function () {
        $rootScope.$broadcast('getStudents', ['Rajesh''Suresh']);
    };

    $scope.$on('runData'function (evt, datas) {
        $scope.data = datas;
    })

});

locapp.controller('childController'function ($scope, $rootScope) {
    $scope.employees = [];

    $scope.$on('getEmployees'function (evt, data) {
        angular.forEach(data, function (item) {
            $scope.employees.push(item)
        });
    });

    $scope.getParentInfo = function () {
        $scope.$emit('runData', ['1''2']);
    };


});

above code cleanly explains the that from the child controller we are calling a method getParentInfo inside that method we are emit a method from child controller to parent controller along with the data. because of emit the parent controller assign a value 1,2 in the array variable data.

Output:
******




From the above code you can learn how to call a method from the child controller to parent controller.

No comments:

Post a Comment