35

In my view, I want to render:

<p>
  {{ say() }}
</p>

Where say is defined as such:

say = function() {
  return "Hello World";
}

I can define it in my controller:

function TestCtrl($scope) {
  $scope.say = function() { ... };
}

But then it's only accessible within that controller.

If I define the function outside the Angular file structure, it renders nothing. Same if I define it in my controllers.js file, but outside a controller function scope.

Where is the proper place to put my function, so I can render it in any controller?

Kyle Macey
  • 8,074
  • 2
  • 38
  • 78

1 Answers1

48

One way is to create a service with the functions you want to share across multiple controllers. See this post for more info.

After you do so you can inject the service you created into any controller and access the say() function with code something like this:

function TestCtrl($scope, myService){
   $scope.say = myService.say;
}

Where you defined myService as:

angular.module('myApp', [])
    .factory('myService', function () {
        return {
            say: function () {
                return "Hello World";
            }
        }
    });

Here is a jsFiddle with an example.

Community
  • 1
  • 1
Gloopy
  • 37,767
  • 15
  • 103
  • 71
  • Awesome... I was expecting it to be in with the services, but couldn't find the syntax to add it in – Kyle Macey Sep 18 '12 at 16:47
  • 5
    Just FYI, an alternate syntax (I prefer seeing/reading 'service' instead of 'factory' if I only need a constructor function): .service('myService', function () { this.say = function () { return "Hello World"; } }); – Mark Rajcok Sep 18 '12 at 17:31
  • 1
    The "problem" with a proper service is that each time you use the service, you get a new instance of that service. In this case it might not be the best idea. – Spock Jul 12 '14 at 14:11
  • 1
    @Spock Yes, so maybe angular should add something like 'singleton bean'. – Evan Hu Jan 16 '15 at 23:43