I'm trying to separate components into several files for a simple application but angular's dependency injector is giving me headaches and I don't really know what is expected.
Unknown provider: servicesProvider <- services <- maincontroller
Is the error I'm getting.
app.js
//Application definition with injected dependencies
var app = angular.module('leadcapacity', ['services', 'utils', 'customfilters', 'controllers']);
services.js
var services = angular.module('services', []);
services.service('xrmservice',
[
'$http', function($http) {
var oDataUrl = Xrm.Page.context.getClientUrl() + '/XRMServices/2011/OrganizationData.svc/';
var service = {};
service.query = function(entitySet, query) {
return $http.get(oDataUrl + entitySet + '?' + query);
};
return service;
}
]);
controllers.js
var ctrls = angular.module('controllers', ['utils', 'services']);
ctrls.controller('maincontroller',
function ($scope, services, utils) {
};
});
And the include order in index.html
<script src="service.js"></script>
<script src="controllers.js"></script>
<script src="app.js"></script>
Looks fine to me. I know this is perhaps not the best way to organize things, but getting a "Hello world" first would be nice.
Thanks.
Error message appearing in console clearly says that, services
dependency isn't exists in the module.
You have injected incorrect service name in maincontroller controller factory function, basically you were trying to to inject services(module name) instead of xrmservice(service name)
function ($scope, services, utils) {
should be
function ($scope, xrmservice, utils) {
Additional
Do follow Inline Array annotation of DI, as you were already used the same in your xrmservice service JS file, so that in future you don't need to go back and change that when you face javascript minification related issues.
Controller
ctrls.controller('maincontroller', [ '$scope', 'xrmservice', 'utils',
function ($scope, xrmservice, utils) {
//code goes here
//....
};
}]);
Although you have injected them into the module, you need to give them to the function so you can use the injected modules
ctrls.controller('maincontroller',
['$scope', 'services', 'utils', function ($scope, services, utils) {
};
}]);
Related
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){
[...]
}
]);
I have an angular module that is designed to be self contained. That a consuming app can add the directives with a url param and it will use that url as it's overall data source when interacting with the widget. This has a generic LoadService that uses $http to load the data, and expects a specific JSON format to run the widget.
Well right now I am trying to refactor so that someone can also create a custom load service and inject it into the module, but if it's not injected then it will use the default data load. So I am trying to figure out how I can create a way that CustomLoadService is injected if it is defined by the app that is consuming the module. However it should not error out if the custom service isn't defined, it should just use the default service.
I was looking into the $injector.get and saw that as a possibility but I am having trouble injecting the $injector into a controller. I thought it would be as simple as $location to inject. Something like...
angular
.module('Widget')
.controller('WidgetController',[
'$scope',
'WidgetLoadService',
'$injector',
WidgetController
]);
This method doesn't seem to work so I am wondering... What is the best most "angular way" to solve this issue. How should I be using the $injector.
You can use $injector:
app.controller('MainCtrl', function($scope, $injector) {
$scope.name = $injector.get('test').name;
}).factory('test', function() { return {name: 'world'} });
So you may have something like this as a result:
app.controller('MainCtrl', function($scope, shareService) {
$scope.name = shareService.getData();
shareService.setDataService('dataService2');
$scope.name = shareService.getData();
})
.factory('shareService', function($injector) {
var dataServiceName;
return {
setDataService: function(name) {
dataServiceName = name;
},
getData: function(name) {
return $injector.get(dataServiceName || 'dataService').data;
}
}
})
.factory('dataService', function() { return {data: 'world'} })
.factory('dataService2', function() { return {data: 'world 2'} });
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]);
}());
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
}]);
});
angular.module('app.services', []).service("test", function($http, $rootScope){
this.test=function(){
$rootScope.name="test1";
};
};
angular.module('app.controllers', []).controller('TestController', function ($scope, test) {
test.send();
})
I dont get an error but the changes don't get applied to the UI. I tried $scope.apply() and got an error.
We need to tell Angular which modules your module depends on, In our case the main module is app.controllers.
To call service from different model we need tell to controller where is our service:
['app.services']
JS
var appServices = angular.module('app.services', []);
var appCtrl = angular.module('app.controllers', ['app.services']);
appServices
.service("test", function ($http, $rootScope) {
this.send = function () {
$rootScope.name = "test1";
};
});
appCtrl.controller('TestController', function ($scope, test) {
test.send();
});
Demo Fiddle
I think you should change ".service" by ".factory".
As I can see in the creating services docs there are 3 ways of creating custom services. One of then is using factory way, as the following:
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
Hope to help.