1

One of the nice things about jQuery is that I can write a function and access it from anywhere within my application. AngularJS appears to be different and it is kind of frustrating. For example, I have the following code on my site:

<div id="myCtrl" ng-controller="myCtrl">
    <div ng-click="doSomething()">click here</div>
</div>

The problem is that doSomething() is defined in a different controller and therefore it doesn't work. This is a common problem that I have run in to and this aspect of AngularJS makes my app more complex than just using pure jQuery to define my functions. How can I call doSomething() from within any controller without having to create a service/factory, etc.? It just seems like that makes everything unnecessarily complicated.

Chris Paterson
  • 1,129
  • 5
  • 21
  • 31

2 Answers2

2

Short answer: you want a service/factory/...

Generally, when you find yourself wanting to call a controller function from a different controller that's a sign you should create a service. You'll really end up with cleaner code that way. Using a service will make it clear to anyone reading your code that that service is needed by whatever controllers it's handed off to.

Having said that, check out: Can one controller call another? (in particular you may like: http://egghead.io/lessons/angularjs-sharing-data-between-controllers)

Community
  • 1
  • 1
KayakDave
  • 24,636
  • 3
  • 65
  • 68
0

There is a reason why controllers can't access each other that way. It's just a kind of separation. The same reason why you don't declare all variables global in other languages.

If you want to do that, you should then have 1 big controller for your whole application, declaring it that way :

<body ng-controller="myCtrl">

</body>

But, I think it's a bad idea, and that you should learn services, factories,...

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66