Angular 1.x service with separate file - angularjs

I have Angular 1.4 service working in app.js but I want to move this service in a separate file. Can anybody advise me a site explaining how to do this? Thanks!

Heres an example of how you can move your service in a separate file.
app.js:
(function(){
// create main app module
angular.module('myApp', []);
})();
controller.js:
(function(){
angular.module('myApp').controller(MyController, MyController);
// inject dependencies here
MyController.$inject = ['MyService'];
function MyController(MyService) {
// controller logic
}
})();
service.js:
(function(){
angular.module('myApp').factory('MyService', MyService);
MyService.$inject = [];
function MyService() {
var service = {};
return service;
}
})();
As for a site with good explanations and best practices, check out the angular 1.x style guide which has been endorsed by the angular team. Specifically pay attention to Style Y001.

Related

AngularJS $injector:unpr issue

im completely new to angularJS, below is the minimal example of my issue:
myModule.module.js:
(function () {
'use strict';
angular
.module('myModule', [
'myServices',
'myControllers'
]);
angular
.module('myServices', []);
angular
.module('myControllers', []);
})();
myService.service.js
(function () {
'use strict';
angular
.module('myModule')
.factory('myServices', myServices);
function myServices() {
var service = {};
return service;
}
})()
myController.js:
(function () {
"use strict";
angular
.module("myModule")
.controller("myController", myController);
myController.$inject = ['myServices']
myController(myServices) {
/* use myServices */
}
})()
I think I accomplished all things needed to make service available to controller but I'm still getting unresolved provider error...
I'm coming from strong Angular2+ background and maybe some common potfall I'm unaware of? Does the tile names os services must match their angular name or something similar?
Any help is appreciated.
Oh yeah, Angular2+ experience strikes on this one. Basically I was absolutely unaware about managing scripts in main.html (or whatever entry point for app is). So basically I was dumb enough not tu supply my main.html with specified script file.
So, assuming that my usecase was to add just another service to already working myModule, then
<script src="path/to/myService.js"></script>
Hope this will help someday some other dev lost in AngularJS :)
Cheers

Angularjs - Uknown Provider

Whenever I do this:
app.controller('hangmanController', ['$scope', 'wordnickAPIService', function ($scope, wordnickAPIService) {
I get this:
[$injector:unpr] Unknown provider: wordnickAPIServiceProvider <- wordnickAPIService
I read through This discussion on the topic, but didn't see an answer that applied. I am sure it is something simple or trivial that I am missing, but, jeez, if Angular isn't giving me fits trying to piece it all together.
Relevant HTML:
<body ng-app="angularHangmanApp" ng-controller="hangmanController">
My controller:
'use strict';
var app = angular.module('angularHangmanApp', []);
app.controller('hangmanController', ['$scope', 'wordnickAPIService', function ($scope, wordnickAPIService) {
[...]variable declarations[...]
var wordListURL = 'http://long_url_that_returns_some_json';
$scope.wordList = wordnickAPIService.get(wordListURL);
}]);
My factory:
'use strict';
var app = angular.module('angularHangmanApp', []);
app.factory('wordnickAPIService', ['$http', function($http) {
return {
get: function(url) {
return $http.get(url);
},
post: function(url) {
return $http.post(url);
},
};
}]);
The problem is that you are creating multiple modules with the same name.
To create a module in angular you use:
var app = angular.module('angularHangmanApp', []);
Then to get That module somewhere else you just type:
var app = angular.module('angularHangmanApp');
No extra []...
Also make sure you declare the service before trying to call it.
In your factory and your controller, you are actually redefining the app module.
Instead of saying
var app = angular.module('angularHangmanApp', []);
say
var app = angular.module('angularHangmanApp');
Use the first style of invocation only once in your application (maybe just app.js). All other references should use the second style invocation, otherwise, you're constantly redefining the angular app and losing all of the controllers, factories, directives declared previously.

AngularJS Dependency Injector

I've been using angularJS for a while now, and I was wondering if it is correct to use the DI this way. Let's say I want to define a service, which needs some angular services. I would probably write the following:
var app = angular.module('myapp', []);
app.service('myService', function($q, $http) {
// Do stuff
});
Is it correct if I write this instead:
var app = angular.module('myapp', []);
app.service('myService', function($injector) {
// DI
var $q = $injector.get('$q');
var $http = $injector.get('$http');
});
I find it clearer and easier to add / remove dependencies.
Thanks for the heads up :-)
It is correct in both ways, for me i prefer to use the first example, because you can inject the dependencies more fast, and in a similar way as you 'inject' modules between your same modules.

Angular add modules after angular.bootstrap

I'm using meteor + angular. My intention is to add more dependencies after the app bootstrap (This is because the package is the one handling the bootstrapping at the start and I don't have much control of it). Now while doing that, I would also want to enforce a basic code structure wherein for example, I would compile all controllers in one module.
Here's the basic idea:
'use strict';
angular.module('app.controllers', [])
.controller('MainCtrl', function() {
// ...
})
.controller('SubCtrl', function() {
// ...
})
.controller('AnotherCtrl', function() {
// ...
});
Then include that to the main module as dependency:
angular.module('app', [
'app.filters',
'app.services',
'app.directives',
'app.controllers' // Here
]);
After some research, I've discovered that what I'm trying to do (Adding dependencies after bootstrap) is actually a part of a feature request to the angular team. So my option is using, for example, $controllerProvider and register() function:
Meteor.config(function($controllerProvider) {
$controllerProvider.register('MainCtrl', function($scope) {
// ...
});
});
Meteor.config(function($controllerProvider) {
$controllerProvider.register('SubCtrl', function($scope) {
// ...
});
});
Meteor.config(function($controllerProvider) {
$controllerProvider.register('AnotherCtrl', function($scope) {
// ...
});
});
It's works though not that elegant. The questions are:
What's a more elegant way of doing the config and register part?
Is there a way to register a module instead?
Create your module:
angular.module('app.controllers', []);
Add it as a dependency:
angular.module('app').requires.push('app.controllers');
according to this presentation (slide 12) you can assign controllerProvider to app.
Example of replacing module's controller method: http://jsfiddle.net/arzo/HB7LU/6659/
var myApp = angular.module('myApp', []);
//note overriding controller method might be a little controversial :D
myApp.config(function allowRegisteringControllersInRuntime($controllerProvider) {
var backup = myApp.controller;
myApp.controller = $controllerProvider.register;
myApp.controller.legacy = backup;
})
myApp.run(function ($rootScope, $compile) {
myApp.controller('MyCtrl', function($scope) {
$scope.name = 'Superhero';
})
var elem;
var scope=$rootScope;
elem = $compile('<p ng-controller="MyCtrl">{{name}}</br><input ng-model="name" /></p>')($rootScope, function (clonedElement, scope) {
console.log('newly created element', clonedElement[0])
document.body.appendChild(clonedElement[0]);
});
console.log('You can access original register via', myApp.controller.legacy);
})
The only method that I've seen that works is replacing the angular.module function with your own function returning the module you used to bootstrap your app.
var myApp = angular.module('myApp', []);
angular.module = function() {
return myApp;
}
So that all modules that are registered afterwards are actually being registered in your myApp module.
This method combined with the one you describe in the question (using providers like $controllerProvider) will allow you to add "modules" after angular.bootstrap.
Demo
See this jsfiddle for a demo: https://jsfiddle.net/josketres/aw3L38r4/
Drawbacks
The config blocks of the modules that are added after angular.bootstrap will not be called. Maybe there's a way to fix this, but I haven't found it.
Overriding angular.module feels like a "dirty hack".

how to manage big angular app

I'm having trouble managing my app. I would like to separate my controllers on several files. I read Brian's Ford blog ( http://briantford.com/blog/huuuuuge-angular-apps.html ) but I cannot quite understand how should I do it.
On my controller.js file I had something like this :
function loginCtrl($scope){
....
}
function landingCtrl($scope){
...
}
And the only way I found to separate controller per file is to do this:
app.js:
var musicApp = angular.module('musicApp', []);
controller1.js:
musicApp.controller('loginController', ['$scope', loginCtrl],function loginCtrl($scope){
....
});
controller2.js:
musicApp.controller('landingCtrl', ['$scope', landingCtrl],function landingCtrl($scope){
....
});
Is there a better way to do this?
I'm using a similar way as below:
Main.js
angular.module('app', []);
FooCtrl.js
angular.module("app").controller("FooCtrl", [
"$scope", function($scope) {
}
]);
Another way adopted by google is:
# init empty Object
var docsApp = {
controller: {},
directive: {},
serviceFactory: {}
};
# FooCtrl.js
docsApp.controller.FooCtrl = ['$scope', function($scope){}]
# BarCtrl.js
docsApp.controller.BarCtrl = ['$scope', function($scope){}]
... add services
... directives
# bootstrap angular
angular.module('docsApp', ['...']).
config(...).
factory(docsApp.serviceFactory).
directive(docsApp.directive).
controller(docsApp.controller);
Take a look at this js from google angularjs tutorial: http://docs.angularjs.org/js/docs.js
You can achieve this in multiple ways.
one file for all your controllers using "."
musicApp.controller('loginController', ['$scope', loginCtrl,function loginCtrl($scope){
....
}]).controller('landingCtrl', ['$scope', landingCtrl,function landingCtrl($scope){
....
}]);
just remember to include the function inside the injected paramenters array.
or one controller for each file.
just need to include every js file with whatever method you are using (script tag, requirejs, etc.)
I have something similar:
main_router.js:
var myApp = angular.module('theApp', ['controllers'])...
var controllers = angular.module('controllers', []);
some_controller.js:
controllers.controller('SomeCtrl', ['$scope',
function ($scope) { ... }
]);

Resources