Anders Lindén Anders Lindén - 1 year ago 115
AngularJS Question

How do I call method in child controller?

I am using angular pager by using

<script type="text/javascript" src="Scripts/angular-pager.js"></script>

In MainController, I have a PagerController like

<div ng-app="myapp" ng-controller="mainController">
<div ng-controller="PagerController as vm" data-entities="Bookings"

That pager controller uses http to populate itself using information in data-entities like

var app = angular.module("myapp", ["ng"])
.controller("mainController", function ($scope, $http, $filter)
/* a lot of code */
.factory('PagerService', PagerService)
.controller('PagerController', function (PagerService, $http, $scope, $attrs)
var vm = this;
var pageSize = $attrs["pagesize"];
var entities = $attrs["entities"];

vm.update = function ()

vm.setPage = setPage;


function initController()

function setPage(page)
$http.get(entities + "/" + page + "/" + pageSize).success(function (result)
var numPages = Math.ceil(result.totalNumItems / pageSize);

vm.pager = PagerService.GetPager(result.totalNumItems, numPages, page);
vm.items = result.items;

When I have done actions in the main controller, I need to update the pager, because the data has changed as a result of those actions. How do I have the pagers' update function called from code inside mainController?

Answer Source

While @Sravan's answer will work, it's better to $broadcast from the current $scope so only this controllers children will receive the event. With $rootScope you will actually $broadcast the event to ALL scopes/controllers.

Also, don't forget to unregister your listener(s) to prevent possible leaks.


  $scope.$broadcast('pageChange', $;


var unregisterPageChangeListener = $scope.$on('pageChange', function(event, updatedPage){
   vm.pager.currentPage = updatedPage;

$scope.$on('$destroy', function() { unregisterPageChangeListener(); }

Though it was not your question, even better still is to communicate between controllers through services/factories.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download