Separate service from controller in Angularjs - javascript

I would like to separate the service from the controller in my angularjs application, I did it in a following way:
the app.js there is:
var myApp = angular.module('myApp',['restangular','ui.router','myApp.controllers','myApp.services']);
the controllers.js:
angular.module('myApp.controllers',[]);
the services.js:
angular.module('myApp.services',[]);
I have a controllers related to the controllers.js:
angular.module('myApp.controllers',[]).controller('ContactController', ContactController);
ContactController.$inject = [ '$scope', 'ContactService' ];
function ContactController($scope, ContactService) {
console.log("here call ctrl contact");
$scope.contacts = ContactService.getAll();
}
This ContactController call the service ContactService defined in a separate file:
ContactService .js
angular.module('myApp.services',[])
.factory('ContactService', function(Restangular){
var Contacts = Restangular.all('contacts');
return {
getAll : function(){
return Contacts.getList().$object;
}
};
});
the problem is when I have tried to invoke this controller I got the following error:
Error: [$injector:unpr] Unknown provider: ContactServiceProvider <-
ContactService
http://errors.angularjs.org/1.2.19/$injector/unpr?p0=ContactServiceProvider%20%3C-%20ContactService
how can I fix that?
UPDATE:
this is the structure of my app:
I have in app.js:
.state('contacts', {
url: '/contacts',
templateUrl: 'templates/contacts.html',
controller: 'ContactController'
})
.state('todos', {
url: '/todos',
templateUrl: 'templates/todos.html',
controller: 'TodoController'
})
in the index.html i imported all th js files:

Once you have initialized a module withm, angular.module('myApp.controllers', []) again you should not use second parameter dependency([])
So,
in your controller,
`angular.module('myApp.controllers',[])` should be `angular.module('myApp.controllers')`
So,
angular
.module('myApp.controllers')
.controller('ContactController', ContactController);
ContactController.$inject = ['$scope', 'ContactService'];
function ContactController($scope, ContactService) {
console.log('here call ctrl contact');
$scope.contacts = ContactService.getAll();
}
The same applies to your service/factory,
angular.module('myApp.services')
.factory('ContactService', function(Restangular){
var Contacts = Restangular.all('contacts');
return {
getAll : function(){
return Contacts.getList().$object;
}
};
});
PS: After seeing the order of your js file injection in index.html I found the major issue.
The order of your file scripts is wrong. In ContactController you are using contactService which is not defined before it.
So change the scripts order in index.html as below.
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/services/ContactService.js"></script>
<script src="js/services/TodoService.js"></script>
<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/ContactController.js"></script>
<script src="js/controllers/TodoController.js"></script>

try to include
angular.module('myApp.controllers',['myApp.services'])
instead of
angular.module('myApp.controllers',[])
cheers

Seems the issue fixed by reorder the import of my js files as follows:
the app.js then the file services and then the controllers.

Related

How to use one module for multiple controllers

How to use one module for multiple controllers, when these controllers are in different js files.
I have 3 js file
1. app.js
2. Login. js
3. Register.js
app.js
var app = angular.module("myApp", ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'Login/login.html',
controller: 'myCtrl'
})
.when('/register', {
templateUrl: 'Register/register.html',
controller: 'registerCntrl'
})
})
Login.js
var app = angular.module("myApp");
app.controller("myCtrl", function ($scope) {
$scope.login = function (data) {
console.log(data);
if (data.name == 'pinku' && data.pswd == '1234') {
console.log("Login Successfull");
} else {
console.log("Not successful");
}
};
$scope.moreInfo = function () {
alert("M in more info");
}
});
Register.js
var app = angular.module("myApp");
app.controller("registerCntrl", function ($scope) {
});
I have defined mymodule in my app.js file now i want to register my controller to that module and controllers are in different class. I have injected ng-Route in app.js. In login m using already defined module but m getting error
'Failed to instantiate module ngRoute due to:'
Thanks in advance
You can rather do:
angular.module("myApp")
.controller(...)
for both the controllers, rather than writing the variable here
Note: app.js should be loaded before any of the controllers for this to work.
This is one of the ways it can be done:
<html ng-app="myApp">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="controller1.js"></script>
<script type="text/javascript" src="controller2.js"></script>
</body>
</html>
Apart from this you can also use some task runners like gulp OR grunt to do that automatically.
If you load your app.js first, in other files you can inject your modules like
app = angular.module("myApp");
Note that I omit [] from the function call. It means that you are trying to get already defined module.

Calling Routes from a js angular 1.5.8 file

I've my backend developed in Silex with various routes that I can fully access using localhost:8080/project/api/index.php/user (example of a route).
if i'm coding an http get(I use only one controller called mainController ) in a js file using angular 1.5.8, how can I make that when I enter angularsite/user
(user is the route, "/user"), it returns me the data and then show it on my index.html ?
You need to set your app routes to your mainController controller.
angular.module('YourProject', [
'YourModule',
'ngRoute'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user', {
templateUrl: 'view.html',
controllerAs: 'mainCtrl',
controller: 'mainController '
});
$routeProvider.otherwise({
redirectTo: '/user'
});
}])
Now when the page loads the RouteProvider will finds the default path to user (default route) route and that will load your view and controller. The templateUrl contains the route to the template.
If you only want to load a partial page you can do something like this..
'use strict';
var App = angular.module('YourProject', ['ngRoute', 'AppControllers']);
App.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/user', {
templateUrl: 'user.html'
}).
otherwise({
redirectTo: '/path'
});
}]);
Since your question mentions an API if you are trying to just load some data you can call user API with something like this from your controller (provided that the url given is an API which accepts GET request and responds with JSON data)..
var AppControllers = angular.module('AppControllers', []);
AppControllers.controller('MainController', ['$scope','$http', function ($scope, $http) {
//Declare a function to fetch user data from API
$scope.user= function () {
var req = {
method: 'GET',
url: baseURL + 'project/api/index.php/user'
}
return $http(req).success(function (data,status,header) {
$scope.user = data;
}).error(function () {
console.log(error);
});
}
//Call the get user function
$scope.user();
}]);
And finally in your partial file (user.html) add the controller to bind it with the controller declared above.
<!doctype html>
<html ng-app="YourProject">
<body>
<head>
<title>User Page</title>
</head>
<div class="user-content" ng-controller="MainController">
</body>
</html>

What's wrong with this factory dependencies issue?

I'm working with AngularJS.
I'd like to get a controller using a first factory which using another one.
It could be schematize like that:
MyCtrl -> Factory1 -> Factory2
So I tried to do in 3 different files (loaded in the following order):
Factory2.js
app.factory('Factory2', function () { ... })
Factory1.js
app.factory('Factory1',['Factory2', function (Factory2) { ... })
controller.js
app.controller('MyCtrl',['$scope', 'Factory1', function ($scope, Factory1) { ... })
And in my HTML I have:
<script src="services/factory2.js" type="text/javascript"></script>
<script src="services/factory1.js" type="text/javascript"></script>
<script src="controllers/controller.js" type="text/javascript"></script>
But it doesn't work and I've got this error Unknown provider: Factory2Provider <- Factory2 <- Factory1
What's wrong with my code? Am I missing something?
You can refactor your codes and use modules, in this way you will not need to use $inject
var app = angular.module('app', ['factories', 'mymodule']);
angular.module('factories', [])
.factory('Factory2', function () { })
.factory('Factory1', ['Factory2', function (Factory2) {
return myCustomFunction = function () {
alert('todo');
}
}]);
angular.module('mymodule', [])
.controller('MyCtrl', ['$scope', 'Factory1', function ($scope, Factory1) {
$scope.text = "testing";
}])
http://jsfiddle.net/kL78rdr3/3/
Why don't you use explicit injection with $inject? It is a better approach, because it gives you more control over the dependencies. For example:
userController.js
function userController (model, routeParams, searchService) {
//implementation
}
userController.$inject = ['$scope', '$routeParams', 'searchService'];
app.controller("userController", userController);
searchService.js
var searchService = function (http, log) {
//implementation
}
searchService.$inject = ["$http", "$log"];
app.factory("searchService", searchService);
This post may be useful: Explicit Dependency Injection

Angularjs controller not found

As I felt my single controller was growing too large I am now trying to make use of multiple controllers. However, my UserController can't be found for some reason when I navigate to /signup. I'm getting this error:
Error: [ng:areq] Argument 'UserController' is not a function, got undefined
app.js
var app = angular.module('myApp', [
'ui.router',
'ngResource',
'myApp.controllers',
]);
angular.module('myApp.controllers', []);
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$stateProvider
.state('signup', {
url: '/signup',
templateUrl: 'views/signup.html',
controller: "UserController"
});
});
I'm including the .js files in this order:
<script src="angular/controllers/mainCtrl.js"></script> //binded to body tag
<script src="angular/controllers/userCtrl.js"></script> //set in signup state
<script src="angular/app.js"></script>
UserController
angular.module('myApp.controllers').controller('UserController', function () {
//do stuff
});
What am I missing?
Make it easier on yourself and create cleaner code.
var app = angular.module('myApp', [
'ui.router',
'ngResource',
'myApp.controllers',
])
.config(function($stateProvider) {
$stateProvider
.state('signup', {
url: '/signup',
templateUrl: 'views/signup.html',
controller: "UserController"
});
});
you weren't using $urlRoutProvider and $httpProvider so why inject them?
Angular Modules are good for nothing...so far. Except for loading 3rd-party angular code into your app and mocking during testing. Other than that, there is no reason to use more than one module in your app.
To create your UserController do a
app.controller('UserController', function ($scope) {
//do stuff
});
<script src="angular/controllers/mainCtrl.js"></script> //binded to body tag
<script src="angular/controllers/userCtrl.js"></script> //set in signup state
<script src="angular/app.js"></script>
You cant use a module before it's declared.so switch the scripts order.
You should stick to 1 independent module declaration per file and you'll be fine,otherwise you'll have to manage script order.
Your app.js has to be declared first like below BEFORE you pull in its controller subcomponents:
<script src="angular/app.js"></script>
<script src="angular/controllers/mainCtrl.js"></script> //binded to body tag
<script src="angular/controllers/userCtrl.js"></script> //set in signup state

Argument 'fn' is not a function got string

I have a part in my angular application on which I've binded a controller,
since then I got the Argument 'fn' is not a function Error, can anyone look at my code and explain why I got that Error?
I would be very gratefull :)
html-markup:
<section class="col-lg-12" data-ng-controller="MessageController">
<fieldset>
<legend>{{ 'MESSAGES' | translate }}</legend>
</fieldset>
<div class="margin-left-15">
<ul class="list-style-button">
<li data-ng-repeat="message in MSG">{{ message }}</li>
</ul>
</div>
</section>
controller:
(function() {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('MessageController', ['$scope', 'MessageService', '$rootScope', function MessageController($scope, MessageService, $rootScope) {
$rootScope.MSG = MessageService.getMessages();
$rootScope.$watch('MSG', function(newValue) {
$scope.MSG = newValue;
});
}]);
}());
Service:
(function() {
'use strict';
var messageServices = angular.module('portal.services');
messageServices.factory('MessageService', ['MessageData', 'localStorageService', 'UserService'], function(MessageData, localStorageService, UserService) {
return new MessageService(MessageData, localStorageService, UserService);
});
function MessageService(MessageData, localStorageService, UserService) {
this.messageData = MessageData;
this.localStorageService = localStorageService;
this.userService = UserService;
}
MessageService.prototype.getMessages = function() {
var locale = this.userService.getUserinfoLocale();
var messages = this.localStorageService.get(Constants.key_messages + locale);
if (messages !== null && messages !== undefined) {
return JSON.parse(messages);
} else {
return this.messageData.query({
locale: locale
}, $.proxy(function(data, locale) {
this.save(Constants.key_messages + locale, JSON.stringify(data));
}, this));
}
};
MessageService.prototype.save = function(key, value) {
this.localStorageService.add(key, value);
};
}());
data:
(function() {
'use strict';
var data = angular.module('portal.data');
data.factory('MessageData', function($resource) {
return $resource(Constants.url_messages, {}, {
query: {
method: 'GET',
params: {
locale: 'locale'
},
isArray: true
}
});
});
}());
order of js files in html head:
<script src="js/lib/jquery-1.10.js"></script>
<script src="js/lib/angular.js"></script>
<script src="js/lib/angular-resource.js"></script>
<script src="js/lib/angular-translate.js"></script>
<script src="js/lib/angular-localstorage.js"></script>
<script src="js/lib/jquery-cookies.js"></script>
<script src="js/lib/bootstrap.js"></script>
<script src="js/portal.js"></script>
The problem was in using the 'wrong' syntax to create the service
instead of using:
messageServices.factory('MessageService',
['MessageData','localStorageService', 'UserService'],
function(MessageData, localStorageService, UserService){
return new MessageService(MessageData, localStorageService, UserService);
}
);
I had to use:
messageServices.factory('MessageService',
['MessageData','localStorageService', 'UserService',
function(MessageData, localStorageService, UserService){
return new MessageService(MessageData, localStorageService, UserService);
}
]);
I closed the array with parameters to soon, and since I'm still learning I didn't see it directly, anyhow I hope I can help others who stumble upon this.
Today I got the same kind of error doing that silly mistake:
(function(){
angular
.module('mymodule')
.factory('myFactory', 'myFactory'); // <-- silly mistake
myFactory.$inject = ['myDeps'];
function myFactory(myDeps){
...
}
}());
instead of that:
(function(){
angular
.module('mymodule')
.factory('myFactory', myFactory); // <-- right way to write it
myFactory.$inject = ['myDeps'];
function myFactory(myDeps){
...
}
}());
In fact the string "myFactory" was brought into the injector who was waiting for a function and not a string.
That explained the [ng:areq] error.
The above answers helped me considerably in correcting the same issue I had in my application that arose from a different cause.
At built time, my client app is being concatenated and minified, so I'm writing my Angular specifically to avoid related issues. I define my config as follows
config.$inject = [];
function config() {
// config stuff
}
(I define a function, $inject it as a module and declare what it is).
And then I tried to register the config just as I registered other modules in my app (controllers, directives, etc..).
angular.module("app").config('config', config); // this is bad!
// for example, this is right
angular.module("app").factory('mainService', mainService);
This is wrong, and gave me the aforementioned error. So I changed to
angular.module("app").config(config);
And it worked.
I guess the angular devs intended config to have a singular instance and by so having Angular not accept a name when config is registered.
I had the same issue and In my case the problem was with angular-cookies.js file. It was in folder with other angularjs scripts and when I have used gulp to minify my js files the error occured.
Simple solution was just to place the angular-cookies.js file to another folder, outside the selected folder to minify js files.
My case
let app: any = angular.module("ngCartosServiceWorker"),
requires: any[] = [
"$log",
"$q",
"$rootScope",
"$window",
"ngCartosServiceWorker.registration",
PushNotification
];
app.service("ngCartosServiceWorker.PushNotification");
I forgot to add requires Array as parameters to service like this
app.service("ngCartosServiceWorker.PushNotification", requires);

Categories