Anders Lindén Anders Lindén - 22 days ago 7
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

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


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 ()
{
setPage(vm.pager.currentPage);
};

vm.setPage = setPage;

initController();

function initController()
{
setPage(1);
}

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

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.

mainController

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

PagerController

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

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

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