Difference between angular as global variable and parameter?

I wrote a factory from Angular. There was a critical mistake for me. I wandered around to fix it. Finally, I cleared this problem ... for no reason. So I need a clear description of the problem with the code below.

Here is my code A:

angular .module('BinD', ['ngSails']) .factory('UserService', function ($sails) { ... }); 

And another B:

 (function (angular) { 'use strict'; angular .module('BinD', ['ngSails']) .factory('UserService', function ($sails) { ... }); })(angular); 

And part of the error:

 (function (angular) { 'use strict'; angular .module('BinD', ['ngSails']) .controller('SignUpCtrl', function ($scope, $window, UserService) { 

code B works well. Code Error message "UserServiceProvider unknown (maybe?)". I really don't know why single-valued code works differently. Let me know about it.

+5
source share
2 answers

End a call. factory in the function should not have any meaning. I think you must have made other changes as well.

In the third code snippet, when you call .module with two parameters, you create a new module. This would replace the module you created in "Code A" or "Code B".

You do not use the same module, but create a new one. Therefore, it makes sense that your UserService does not exist in the new module.

Your last fragment should call .module('BinD') with only one parameter. Just the name of the module you want to use.

 angular .module('BinD') .controller('SignUpCtrl', function ($scope, $window, UserService) { 


Another option is that you only .module once and save it.

 var app = angular.module('BinD', ['ngSails']); 

You can then call app.controller or app.factory without worrying about the syntax.

+3
source

In your Code A or Code B in both parts, you created one BinD module with the BinD dependency, and then you register the factory with this module, but Code A will declare the variable globally if you use it, and Code B will encode using the IIFE pattern, which will make your variable available inside the function declared only. But this is not related to your mistake that you get.

Inside your controller, you want to use this factory, but while you are creating a controller , you should not create a new module, for example, by making angular.module('BinD', ['ngSails']) , which will clear the previously registered factory (or other components) with the BinD module and create a new module named BinD . Therefore, after entering the UserService inside your controller, the $injector error is thrown because the UserService not available inside this module.

controller

 (function (angular) { 'use strict'; angular .module('BinD') //<- utilizing already created module .controller('SignUpCtrl', function ($scope, $window, UserService) { 
+2
source

All Articles