Ionic controller arguments


#1

Hi, I’m new to ionic (and angular), quick question: sometimes I see something like this on a controller:

controller(‘MyCtrl’, function($scope, $ionicPlatform) { … }

and sometimes this:

controller(‘MyCtrl’, function($scope, $ionicModal) { … }

What determines what is passed as the 2nd parameter? I wasn’t able to find documentation that clearly explains this. TIA!


#2

These aren’t really arguments, they are dependencies you are injected into your controller. Read up on it here: http://henriquat.re/basics-of-angular/services-dependency-injection/services-and-dependency-injection-in-angularjs.html


#3

In that function you pass the services the controller uses.

The whole and corrected syntax would be:

controller('MyCtrl', [
  '$scope',
  '$ionicModal',
  function($scope, $ionicModal) { ... }
]);

One example uses the ionicPlatform service and the other one the ionicModal service.
maybe you should read into some basic angularjs tutorials.

greetzs, bengtler


#4

That makes more sense. So this would be valid yes?

controller('MyCtrl', [
  '$scope',
  '$ionicModal',
  '$ionicPlatform',
  function($scope, $ionicModal, $ionicPlatform) { ... }
]);

And in the case the full syntax is not used:

controller('MyCtrl', function($scope, $ionicModal, $ionicPlatform) { ... }

Angular still figures out the right thing to do? (from the variable names)

[edit] this sentence from the above link cleared it up for me:

AngularJS injects all parameters whenever a controller is instantiated.


#5

Yep, the “short” syntax works for all preloaded stuff. like you are including ionic first and then your controller is loaded.

But i prefer it to write all dependencies in the full syntax to avoid problems if you forget something to load and so on or for minification.