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.


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

    <div ng-controller="parentController" class="well">
            <li ng-repeat="dt in data">{{dt}}</li>
        <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">
                <li class="well-sm" ng-repeat="emp in employees">{{emp}}</li>
                <div class="btn btn-info" ng-click="getParentInfo()">Call Parent Controller Method</div>

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

<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>




From the Controller side

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

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

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

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

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


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

    $scope.$on('getEmployees'function (evt, data) {
        angular.forEach(data, function (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.


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

No comments:

Post a Comment