How do you inject services from required modules into module config function? - javascript

I have a separate services module and I need a service injected into the config function of a dependent module.
angular.module('app', ['app.services'], function(myservice) {/*use myservice*/})
.controller('mycontroller', function($scope, myservice) {
$scope.message = myservice.sayHello();
});
angular.module('app.services', [], function($provide) {
$provide.service('myservice', function() {
return {sayHello: function() { return 'hello'; }};
});
});
I've also create a fiddle: http://jsfiddle.net/FzGmL/
The code will blow up with Unknown provider: myservice from app
If you remove the myservice argument from the app module config function, the mycontroller constructor function is able to have myservice injected just fine.
How can myservice be injected into the config function of the app module?

You're looking for the Module.run() method, It does initialization work for you after the injector is done loading.
angular.module('myApp', ['app.services'])
.run(function(myservice) {
//stuff here.
});

Related

Call angular service in another js file

I have some javascript and html files: User.js, index.html, Door.js
I want use any function in User.js file.
My user.js file
My door.js file
I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service
Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController
var doorApplicationLoginPage = angular.module("PerioLoginPage", []);
doorApplicationLoginPage.service('UserService', function () {
this.getUserInfo = function () {
alert("getUserInfo");
}
this.reLoginUser = function () {
alert("reLoginUser");
}
});
var doorApplication = angular.module("PerioDoorApplication", []);
doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {
UserService.getUserInfo();
});
Thank you.
You are injecting a service which is not referenced to your module.
See:
The UserService service is referenced in PerioLoginPage module
The PerioMainController controller is referenced in PerioDoorApplication module.
You've got either to:
reference the service in the same module as your controller.
inject the module where service is referenced to the module where controller is referenced.
In this case I can see you have two modules Periodicloginpage and periodicdoorapplication. So two services are defined in two modules. So you have to put the Periodicloginpage as dependency of periodicdoorapplication.
var doorApplication = angular.module("PerioDoorApplication", ["PerioLoginPage"]);
As I said in my comments you have two things to do at least:
You need to return the functions you want to use from the service (UserService):
return{
getUserInfo: getUserInfo,
reLoginUser: reLoginUser
};
Your module needs to reference the one the service is defined on:
angular.module('PerioDoorApplication', ['PerioLoginPage']);
And in your 'PerioMainController', a better way to write it would be:
doorApplication.controller('PerioMainController', ['$scope', '$http', '$sce', 'UserService',
function($scope, $http, $sce, UserService){
[...]
}
]);

Using Browserify with Angular JS - - Passing a service into a Controller

As the title suggests I've recently started a new project where I'm using Browserify (and Gulp) to concatenate my Angular JS files (and the Angular sourcefile) into a single file - bundle.js.
I've decided to split my controllers, services and directives into separate files and then "require" them into my app.js file using Browserify like this:
(function () {
'use strict';
require('angular');
var tabCtrl = require('./controllers/tabs'),
dataService = require('./services/');
angular.module("citiToolsApp", [])
.service('dataService', ['$scope', dataService])
.controller('TabController', ['$scope', tabCtrl]);
}());
However when I try to access my service - dataService - from within my Tab Controller like this:
module.exports = function($scope, tabController) {
dataService.getPrograms(function (response) {
console.log(response.data);
});
};
I get an undefined error. I believe I need to pass dataService into the tabController but I'm unsure on the syntax to do this. Can anyone help with this?
Thanks
EDIT
I've also added the contents of my service file for further detail:
module.exports = function($http) {
this.getPrograms = function(callback) {
$http.get('/programs')
.then(callback);
};
};
I've realised my own mistake. I needed to pass in $http rather than $scope. So instead of:
(function () {
'use strict';
require('angular');
var tabCtrl = require('./controllers/tabs'),
dataService = require('./services/');
angular.module("citiToolsApp", [])
.service('dataService', ['$scope', dataService])
.controller('TabController', ['$scope', tabCtrl]);
}());
It should be:
(function () {
'use strict';
require('angular');
var tabCtrl = require('./controllers/tabs'),
dataService = require('./services/');
angular.module("citiToolsApp", [])
.service('dataService', ['$http', dataService])
.controller('TabController', ['$scope', tabCtrl]);
}());

Angular module loading error

I have an angular project that I'm breaking out into a better file structure but I'm getting Argument 'fn' is not a function, got undefined for an error when creating a new service. Any ideas what I'm doing wrong?
app.js
angular.module('app', [
'app.controllers'
]);
angular.module('app.controllers', ['leaflet-directive', 'app.services']);
angular.module('app.services', []);
main.controller.js
angular.module('app.controllers')
.controller('MainCtrl', MainCtrl);
function MainCtrl($scope, $window, leafletData, DataService) {
var main = this;
main.items = DataService.GetItems();
//Other controller stuff
};
data.service.js
angular.module("app.services")
.factory('DataService', DataService);
var DataService = function(){
return data = {
getItems: function(){
return [//data here];
}
};
}
Your declaration of DataService is the problem. You're declaring it after you're using it. You should change your declaration of DataService to function DataService() instead of setting it to a var to take advantage of function hoisting

How to create module in angularjs

In all the angularjs tutorials I am gone through. Modules are created as follows
var newApp = angular.module('articles', []);
or
var routerApp = angular.module('routerApp', ['ui.router']);
I started my project with meanjs boiler plate code and controller starts as follows
angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
function($scope, $stateParams, $location, Authentication, Articles) {
$scope.authentication = Authentication;
.....
.....
]);
When I change it to
var newApp = angular.module('articles',[]);
newApp.controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
function($scope, $stateParams, $location, Authentication, Articles) {
$scope.authentication = Authentication;
.....
.....
]);
All the routes of articles stops working. If I want to include a new component into the module, how do I do it. I want to add angularFileUpload in to my module.
Sample code in angularfileupload is
angular
.module('app', ['angularFileUpload'])
.controller('AppController', function($scope, FileUploader) {
$scope.uploader = new FileUploader();
});
How do I add ['angularFileUpload'] if the module is already registered?
Edit:
articles.client.modules.js
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('articles');
angular.module("MyModule", []) (with []) is a setter function, that is - it registers a module.
angular.module("MyModule") without [] is a getter function, it retrieves a previously registered module.
Calling a setter twice re-defines the module.
I'm not familiar with meanjs boilerplate, but in all likelihood when you used a setter, you have redefined the module and whatever controllers, services, config, etc... that were previously registered were overwritten.
All you need to do is change what you added to:
var newApp = angular.module("articles");
Example:
angular.module("M", []).controller("A", function(){}); // module M has controller A
angular.module("M").controller("B", function(){}); // module M has controllers A, B
var app = angular.module("M", []); // module M re-registered
app.controller("C", function(){}); // module M has controller C only
// Create a new module
var myModule = angular.module('myModule', []);
// register a new service
myModule.value('appName', 'MyCoolApp');
// configure existing services inside initialization blocks.
myModule.config(['$locationProvider', function($locationProvider) {
// Configure existing providers
$locationProvider.hashPrefix('!');
}]);
Usage
angular.module(name, [requires], [configFn]);

All AngularJS Controllers Not Loading with LazyLoad

I am trying to lazy load my controllers for my AngularJS app I built along side with requireJS. I have created a custom "lazyLoad" library that creates a resolve object in app.config() routes (also I am using ui-router). If I code the state (without my library) to look like so it works
define(['angular', 'lazyLoader', 'uiRouter'], function(angular, lazyLoader, uiRouter){
var app = angular.module('myApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
window.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
$urlRouterProvider.otherwise('/');
$stateProvider
.state('campaigns', {
url:'/campaigns',
views: {
"top-nav" : {
templateUrl: 'views/home/top-nav.html',
resolve : {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require(['../app/controllers/header-controller'], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
}
},
"fullpage": {
templateUrl: 'views/home/index.html',
resolve : {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require(['../app/controllers/home-controller'], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
}
//controller: 'home-controller'
}
}
});
});
return app;
});
If I attempt to replace the resolve object with my library function it looks would look like this:
define(['angular', 'lazyLoader', 'uiRouter'], function(angular, lazyLoader, uiRouter){
and
.state('home', lazyLoader.route({
url:'/',
views: {
"top-nav" : {
templateUrl: 'views/home/top-nav.html',
controllerUrl: '../app/controllers/header-controller'
},
"fullpage": {
templateUrl: 'views/home/index.html',
controllerUrl: '../app/controllers/home-controller'
}
}
}));
lazyLoader.js
define(function () {
'use strict';
function LazyLoader() {}
LazyLoader.prototype.route = function(config){
var controllerPath;
if(config && config.views){
var singleView = Object.keys(config.views);
for(var i in singleView){
var viewName = singleView[i];
controllerPath = config.views[viewName].controllerUrl;
delete config.views.controllerUrl;
config.views[viewName].resolve = {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require([controllerPath], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
};
}
}
return config;
}
return new LazyLoader();
});
Example Controller
define(['app/module'], function (module) {
lazy.controller('header-controller', ['$scope', function ($scope) {
// stuff here
}]);
});
On a side note I plan on implementing something better than attaching lazy variable to window.
When I code the router like the first example it works. When I use my lazyLoader the one of the two views loads it's controller, the second view's controller's file is started to load (console.logs at the beginning show this) but it cannot resolve "module" in the example above.
link to error: AngularJS Error
Again this issue only happens when using my lazyloader which is producing the same resolve object that I have hard coded in for the version that works.
I have searched high and low and there are a lot of resources out there but I could not find anything that addressed this issue.
Any advice is appreciated!
You are taking too much pain to do lazy loading of controllers & services. There is simple approach to lazy load files with ocLazyLoad. This article might help you resolve the same issue.
https://routerabbit.com/blog/convert-angularjs-yeoman-spa-lazyload/
What you should do is
Add a reference of ocLayzLoad & updated JS files’ reference to load on demand from app.js or .html file of their views.
`bower install oclazyload --save-dev`
Now load the module ‘oc.lazyLoad’ in application. Update app.js file
angular
.module('helloWorldApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'oc.lazyLoad',
])
Load JS file by adding reference of JS in .html file
<div oc-lazy-load="['scripts/controllers/about.js', 'scripts/services/helloservice.js']">
<div ng-controller="AboutCtrl as about">
Your html goes here
</div>
</div>
If you using Grunt, update Gruntfile to uglyfy, renamed file name & update references in the final .html or .js file.
On the 'myApp' module definition, shouldn't you be returning app variable instead of myApp?
And to avoid exposing lazy to window, you could define it as a property of app variable, this way when you define new functions, you require app first and you can use it:
app.js:
app.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.register,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
...
return app;
controller.js:
define(['app'], function (app) {
app.lazy.controller('header-controller', ['$scope', function ($scope) {
// stuff here
}]);
});

Categories

Resources