Angular.js - Sharing data between controllers


A lot of times my friends ask me - "How do we share data between controllers in Angular.js?"

Since services in Angular.js are injectable singletons, they seem like a good choice for sharing mutable data. But nothing is worth anything without some code. So here goes -


<div class="row">
  <div class="span12" ng-controller="MainCtrl">
    <h2>Hello {{name}}!</h2>

<div class="row" ng-controller="AnotherCtrl">
  <div class="span12">
    <h2>Greetings from {{name}}!</h2>

'use strict'

class MainCtrl

  constructor: (@$scope, @helperService) ->
    @$ = "World"

MainCtrl.$inject = ["$scope", "helperService"]
angular.module("demoApp").controller "MainCtrl", MainCtrl

'use strict'

class AnotherCtrl

  constructor: (@$scope, @helperService) ->
    @$ = @helperService.getName()

AnotherCtrl.$inject = ["$scope", "helperService"]
angular.module("demoApp").controller "AnotherCtrl", AnotherCtrl

Finally, the

'use strict'

class HelperService

  constructor: () ->

  setName: (name) ->
    @name = name

  getName: ->

angular.module "demoApp.helperService", [], ($provide) ->
  $provide.factory "helperService", -> new HelperService()

It works! QED :)

AngularJS Controllers