AngularJS: How to have different Services/Controllers in same Module? - angularjs

I have a Service and a controller in my AngularJS App, that should be in the same module, but are two different files:
// File 1 (Service)
angular.module('myService', ['ngRoute'])
.service('myService', // ...
// File 2 (Controller)
angular.module('myController', ['ngRoute'])
.controller('myController', // ..
This works fine. Now I want to have Service & Controller in one Module so I can load just one instead of two Modules. So I change the first line (of both files) to:
// Change in both files:
angular.module('myModule', ['ngRoute'])
But now I get an error:
Error: [$injector:unpr] ...
Maybe somebody knows, what could be wrong here. Thank you very much!

You can do the following:
var myApp = angular.module('myApp', []);
myApp.controller("myService"
myApp.service("myApp")
Or
angular.module("myModule").controller
angular.module("myModule").service
If you use angular.module('myService', []) twice, you are initializing the same module twice.
If you just use angular.module("myModule"), without the dependencies, you are just calling it.

You have two options -
use a variable as mentioned by Michael
OR
Use it like -
// Initialize myService Module in any JS file
(make sure this file is included before File 1 and File 2
angular.module('myService', ['ngRoute']);
// File 1 (Service)
angular.module('myService').service('myService', // ...
// File 2 (Controller)
angular.module('myService').controller('myController', // ..

Related

Angular - Issue in moving service into separate file

I have a service with a few methods:
function userService($http, API, auth) {
....
}
and then used in my module like:
var app = angular.module('app', ['ngRoute'])
.service('user', userService)
...
All of this is in my app.js file, I want to separate things so its easier to maintain. I'm trying to use the line .service('user', '/services/userService') but its not working any ideas how to i need to reference this?
Thanks.
I think you are creating a new module instead of use yours.
To retrieve an existing module and use it in a separated file, you have to do :
var app = angular.module('app')
.service('user', userService')
// ...
Instead of
var app = angular.module('app', ['ngRoute'])
.service('user', userService')
// ...
Documentation available at https://docs.angularjs.org/guide/module#creation-versus-retrieval
EDIT from #koox00 answer
Don't forgot to load all files related to your module in your markup, in the good order (before load the file containing your module declaration).

How can I obfuscate AngularJS codes?

How can I obfuscate AngularJS codes?
We have tried gulp-obfuscate, but it does not work. Anyone can help us? Thanks a lot!
We have done like this
someModule.controller('MyController',[ '$scope', function($scope) {",
but after success to get the obfuscated codes like this
function H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅4() {
var H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅1, H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅2, H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅3;
...
H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅3 = H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅1 + H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅2;
return H͇̬͔̳̖̅̒ͥͧẸ̖͇͈͍̱̭̌͂͆͊_C͈OM̱̈́͛̈ͩ͐͊ͦEͨ̓̐S̬̘͍͕͔͊̆̑̈́̅3;
}
all angularjs codes in app-52143d391a.js not worked, it return
Uncaught Error: [$injector:nomod] Module 'client' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
After run
gulp.task('obfuscate', function () {
return gulp.src('../webapp/scripts/app-*.js')
.pipe(ngAnnotate())
.pipe(obfuscate())
.pipe(gulp.dest('dist'));
});
all are ok, and get below codes:
http://pan.baidu.com/s/1ntXuGbB
then run with below error:
Uncaught TypeError:  _ 206. _ 252 is not a function(anonymous function) # app-6c38d9a2fc.js:2
generated.js:9279Uncaught Error: [$injector:modulerr] Failed to instantiate module client due to:
Error: [$injector:nomod] Module 'client' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.7/$injector/nomod?p0=client
From the ngDocs:
Careful: If you plan to minify your code, your service names will get
renamed and break your app.
To make your code work after minification you have to use the inject property, every-time you use dependancy injection, to annotate your components. So even if the variable names change angular will know how to map the mangled variables with the proper service.
e.g:
Here we pass the $scope with dependency injection:
someModule.controller('MyController', function($scope) {
For this line to work you have to change to this:
someModule.controller('MyController',[ '$scope', function($scope) {
Or:
MyController.$inject = ['$scope'];
someModule.controller('MyController', function($scope) {
Or even better.
Use gulp-ng-annotate before the obsfucate task which does all that work for you.
UPDATE
After Obsfucation you should see the $inject string as they where, instead this plugin obsufucates them also. Meaning:
['$http', function($http) {
becomes:
[ "ಠ_ಠ727", function( ಠ_ಠ727 )
instead of:
[ "$http", function( ಠ_ಠ727 )
There is a relevant issue on github
I would suggest you use another plugin. With gulp-uglify I didn't have any issue.

Best practices to inject custom module in meanjs

As I understood there is no classical registration of module, where we can inject our dependencies like:
var myModule = angular.module('myModule', [otherModule]);
However there are file module-name.client.module.js at the root of the directorys
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('module-name');
Can I inject here my module like *.registerModule('module-name', [someModule]); or I should do it in angular.module('articles').config(...)?
But in config I can inject only providers, without factories
As far as i used angular, the best practice to load custom module and external library
is to combine angularjs with requirejs.
It's done in 3 step.
First, load in your main html file a js file which builds the foundation of your system (require.config):
Here you have all the parameters allowed : https://github.com/jrburke/r.js/blob/master/build/example.build.js
Example :
In your html file :
<script src="path/to/require.js" data-main="path/to/yourBuildFile"></script>
In yourBuildFile file :
require.config({
// you can define suitable names for all your external js library
paths:{
// don't put a ".js" at the end of the file
'angular' : 'path/angular',
'underscore' : 'path/underscore-min',
'...': '...',
},
// and other useful things
});
Second, in the same file or in another (see the parameter deps in link above), bootstrap your app:
Like explained here : https://docs.angularjs.org/guide/bootstrap
Example:
// AMD module injection, more info here : http://requirejs.org/docs/whyamd.html
define([ // inject all the external library you need + the definition of your app
'angular',
'require',
'yourpath/yourApp' // don't bother here, it's explained in third point
], function(angular){
// link your app to the document file programatically
angular.bootstrap(document, ['nameOfYourApp']);
});
Third, you define your app (in the "yourpath/yourApp")
Example:
define([
'angular',
// put all path to your directives + controllers + services
], function(angular){ // only specify parameters the library you use in the function
// you create your sublime app :)
angular.module('nameOfYourApp', [
// put all the name of your modules injected above
]);
});
The example above is made for single page application.
You can find other examples for multipage application here
http://requirejs.org/docs/start.html

AngularJs can't inject $provide and $injector services in module.run

I'm trying to define services dynamically in angularjs, as the docs says, $provide and $injector are services, thus they should be injectable in module.run..
I need to make the dynamic services available from app bootstrap, that's why i'm trying to define them in module.run
angular.module('remote.interface',[])
.run(['$provide', '$injector', function(provide, injector){
// provide dynamically
}]);
but this ends up in an Error : [$injector:unpr] Unknown provider: $provideProvider <- $provide, and same eror for $injector if i try to remove $provide injection.
Where's the bug?
[EDIT]
after some research i tried something like this:
var module = angular.module('remote.interface',[])
.run([function(){
var provide = module.provider(),
injector = angular.injector();
provide.value('my.val',{i:'am a value'});
injector.get('my.val'); // this throws [$injector:unpr] Unknown provider: my.valProvider <- my.val
}]);
even if i remove the injector.get call, if i try to inject my.val, for example, in another-module's controller, angular throws the same error.
Have a look at the documentation for module and have a read at the comments in the example setup, particularly these comments.
config
You can only inject Providers (not instances) into config blocks
run
You can only inject instances (not Providers) into run blocks
Here is an example setup on JSFiddle injecting $provide and $injector correctly.
https://docs.angularjs.org/guide/module
angular.module('myModule', []).
config(function(injectables) { // provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
run(function(injectables) { // instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into run blocks
});

Adding new Module is not working in angularjs

i am trying to add a new Module to my application.
My HTML for index page is
<body ng-app="com.app">
In my app.js
angular.module('mod1', ['ngResource']);
angular.module('mod2', []); //this is module i want to add
var app = angular.module('com.app', ['ngResource','mod1','mod2']);
My Controllers1.js
var Controllers = angular.module('mod1');
Controllers.controller('ctrl1', function($scope,$http) {});
Controllers.controller('ctrl2', function($scope,$http) {}); //function for module 2
when i try to add this ctrl2 to my "controllers1.js" it works , but if i add this in my other js say "controllers2.js", its not working .
My controllers2.js is
'use strict';
var mymodule = angular.module('mod2');
mymodule.controller('ctrl2', function() {
console.debug("Testing...");
});
summary of my question is : when i try to add my ctrl2 function to new module, its not working and on firefox console i am getting error
Error: Argument 'ctrl2' is not a function, got undefined
assertArg#http://localhost:8080/tm-webapp/resources/lib/angular.js:1039
assertArgFn#http://localhost:8080/tm-webapp/resources/lib/angular.js:1050
#http://localhost:8080/tm-webapp/resources/lib/angular.js:4802
update#http://localhost:8080/tm-webapp/resources/lib/angular.js:14198
Scope.prototype.$broadcast#http://localhost:8080/tm-webapp/resources/lib/angular.js:8307
updateRoute/<#http://localhost:8080/tm-webapp/resources/lib/angular.js:7463
qFactory/defer/deferred.promise.then/wrappedCallback#http://localhost:8080/tm-webapp/resources/lib/angular.js:6846
qFactory/defer/deferred.promise.then/wrappedCallback#http://localhost:8080/tm-webapp/resources/lib/angular.js:6846
qFactory/ref/<.then/<#http://localhost:8080/tm-webapp/resources/lib/angular.js:6883
Scope.prototype.$eval#http://localhost:8080/tm-webapp/resources/lib/angular.js:8057
Scope.prototype.$digest#http://localhost:8080/tm-webapp/resources/lib/angular.js:7922
Scope.prototype.$apply#http://localhost:8080/tm-webapp/resources/lib/angular.js:8143
done#http://localhost:8080/tm-webapp/resources/lib/angular.js:9170
completeRequest#http://localhost:8080/tm-webapp/resources/lib/angular.js:9333
createHttpBackend/</xhr.onreadystatechange#http://localhost:8080/tm-webapp/resources/lib/angular.js:9304
I am stuck here for a long, kindly help me i shall be very thankful.
Regards,
Make sure that in your file loader (script tags, requirejs, whatever) Controllers1.js is right next to controllers2.js.
PS: some operating systems / webservers (e.g. the server inside karma on windows) are case sensitive. So try to use same case for your files (either upper or lower).
You can try this plunker http://plnkr.co/edit/tKIPDQ54JDexB7LAJpDR to see if it works in the way you want.

Resources