Using AngularJS $apply to call functions across different controllers within same module

Intro.

If you read my old post about Splitting Application Page into Separate AngularJS MINI Components , you might need to also read this post as i am talking here about a way to call a controller function from different $scope using the $apply module (Digest Loading).

Why we might need this?

This is important when we are inside a $scope of controller of a directive or what ever and we need to call or execute another controller $scope function to get or post or what ever the function does.

Indeed you can use the AngularJS $rootscope but all am doing here is introducing another solution.

How to do it ?

Lets assume that we have two different Controllers assigned to two different Directives and two different modules, and from the first Controller ($scope) we need to call function inside second Controller ($scope).

In real case, this could be a “Menu Controller Btn.” toggles “Body Controller Div” Visibility  or what ever you might need.

This is a way to access another $scope functionality without changing the $scope.

First, assuming that the external $scope that we need to call a function inside is assigned to HTML Div or whatever with Class or Id, we need this to get the element assigned $scope by element ID or Class Name.

Note that all the following code snippets should be inside the first controller not the one the function implemented inside.

var externalScope = angular.element($("#comp-body")).scope();

I assumed here that we have an HTML Element with Id = comp-body and this element Controller is the one we seek its functions.

Then lets call the function inside this scope as if we are inside it

externalScope.$apply(function () {
 externalScope.doSomething();
});

Note that, doSomething should be in externalScope ($scope) or implemented this way:

$scope.doSomething = function()
{
//What ever ...
};

Important Note

In some cases you might need to add the last code snippet inside

$timeout(function () {
//put the $apply code here ...
});

to make sure you are not conflicting with same $scope in progress process.

 

Thanks,

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s