Skip to main content

Communicating between controllers in AngularJS

I have seen many solutions to how to make controllers talk to each other whilst at the same time remaining within "da rulez" of writing Angular applications.
I have been using Angular for about a month now and at times it has been swearier than a good Haskell session, it is most definitely worth it all in the end. I have written a really nice looking web application for my employer and they seem to like it. I think Angular.
One thing I really aced (to my own satisfaction at least) was wrapping a REST (of any type) API using a resource. I will make a separate post about that.

Do the simplest thing...

Here is my own solution to the problem of how you can make different controllers communicate cleanly using the "event" system that Angular provides. All you have to do is ensure that the following event listener is added to your application root-scope:
App.run( function( $rootScope )) {
    $rootScope.$on('broadcast', function( e, data ) {
        if (undefined == data.with) {
            $rootScope.$broadcast(data.say);
        }
        else {
            $rootScope.$broadcast(data.say, data.with);
        }
    });
});
There is of course a calling convention now but it is very very simple indeed and should not cause any undue hardship. It allows any normal data to be passed around, here is the format of the object that you must pass as the only argument
    {
        say: 'message-identifier',
        with: message-data (optional)
    }

How it does what it does...

If you read the (improving) documentation closely you will know that $emit() ripples messages up the scope hierarchy and $broadcast goes the other way. As we have added this to the root-scope it means that when the message arrives and is re-dispatched, it's going to go back down to every scope that is currently alive and listening. And that is how we achieve the seemingly impossible task of leaping between branches of a tree, which is essentially what communicating between controllers is all about.

Using it, an example...

I am currently writing a stop-motion web application so I can make the next block-buster Lego animation film. I use Linux and having used what appears to be the only Linux stop-motion program available ("stopmotion") and having found it to be a little unstable and buggy at times I did what any self-respecting hacker would do (next to fixing those bugs!), which is "roll your own".
I have a window that shows the video from the camera and a "configure" button that replaces the camera image with a configuration dialog in the same space. My issue was how to tell the rest of the UI that the user had toggled a checkbox, because the state of the checkbox had to cause the UI to make some changes.
All I had to do with my simplest-thing-possible broadcast helper was send an event like this:
[code] $scope.toggleIPCam = function() { $scope.isIPCam = !$scope.isIPCam; $scope.$emit('broadcast', { say: 'IPCamMode', with: $scope.isIPCam }); }; }; [code] Don't forget that the value for with can be any valid data type, the example shows a boolean being passed but it could as easily have been a function or an object etc.
Here is how we catch it and deal with it...
    $scope.$on('IPCamMode', function(ev, mode) {
        console.log("received mode change on camera: "+mode);
        $scope.isIPCam = mode;
    });
How difficult is that? And remember that if you didn't pass any data then you can dispense with having to declare anything at all after the event parameter and of course, if you don't care about the event then you don't need any formal parameters at all!
So there you have it, inter-controller communications in one simple addition to $rootScope at the cost of following a very simple calling convention.
Hope that helps fellow AngularJS jockeys everywhere.

Comments

  1. I was using services prior to reading your post. I think your way is simpler. Services are kind of overkill for single variable models. Thanks for this tip!

    ReplyDelete
  2. Services are probably the more AngularJS way to go but like you sometimes it seems like overkill.

    If I was writing an very large app that relied on IPC like this a lot then a service would probably better but sometimes you just have to get things done.

    ReplyDelete

  3. Angularjs is a structural framework for developing the dynamic web applications. Angular's data binding and dependecy injection is capable of eliminating much of the code.
    angularjs training in chennai | angularjs training chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

PHP and Lisp: multiple-value-bind (MVB)

This is another article in my attempts to find new ways of looking at PHP and making it less of a chore to type in all that code. As much as I love PHP I hate wasting keystrokes. More typing is more errors is more grief. Being an off and on user of Lisp, although not as much as I used to, one of the things that I always liked in Lisp was the ability to be able to return multiple values from a function at once using (values) and then marry that with (multiple-value-bind) to create convenient named bindings for whatever you were about to do. I recently found myself wanting to return a couple of values from a helper function and I just didn't want to go to the trouble of having to type all those character required to create an array with keys for the two values and then I remembered MVB and a little light went on in my head! If somebody else has already done this then I apologise up front but it was new to me and I haven't seen it anywhere else so this could be a first! ...

Angular.JS ... absolutely awesome BUT...

Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaagh! Sort the documentation soon please!  More soon, I really do like it though. :)

Cross platform development with Scheme

Just a quick note about something I recently found whilst trying not to buy MOCL… http://www.lambdanative.org/ LambdaNative is developed and maintained by the Pediatric Anethesia Research Team (PART) and the Electical and Computer Engineering in Medicine (ECEM) group at the University of British Columbia (UBC). I have spent a week or two evaluating it and accidentally contributed a pull request that got merged and one that didn’t and I have to say that, for what it offers, it is awesomely good. Having personally spent many hours with it now, I do not yet think it is ready for mainstream development for a few reasons. I don’t mean that it a bad way either. What I mean is that the language, Scheme, is not really that widely known and as such it probably won’t break out into the public arena any time yet. That’s a real shame because I think that they have achieved an amazing thing; total abstraction of the underlying platform with a really powerful, underestimated language. ...