How to use one module for multiple controllers - javascript

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.

Related

Separate service from controller in Angularjs

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.

$ionicPlatform.ready not firing

Im having a problem, the code inside $ionicPlatform.ready is not firing if I add my router file and the controller file but I can not find the problem.
Template and controller is working fine.
index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/core/router/app.router.js"></script>
<script src="js/feature/notification/notification.js"></script>
<body ng-app="app">
<ion-nav-view></ion-nav-view>
</body>
app.js
angular
.module('app', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
console.log('##################');
});
});
app.router.js
angular
.module('app', ['ionic', 'ui.router'])
.config(Router);
Router.$inject = ['$stateProvider', '$urlRouterProvider'];
function Router($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('notifications', {
url: '/',
templateUrl: 'js/feature/notification/notification.html',
controller: 'NotificationCtrl',
controllerAs: 'model'
});
}
notifications.js
angular
.module('app')
.controller('NotificationCtrl', NotificationCtrl);
function NotificationCtrl() {
var model = this;
console.log('Test');
}
Thanks for your time
The code wrapped in $ionicPlatform.ready does not run because you are defining your app module more than once when it should only be defined in your app.js. Subsequent calls to the module should leave off the dependency annotations. In this case, you can change the line in app.router.js from .module('app', ['ionic', 'ui.router']) to .module('app').
Another thing to note is that with Ionic, you don't need to inject ui-router yourself as it is included in the Ionic bundle.
You should not, however, remove Router.$inject = ['$stateProvider', '$urlRouterProvider']; unless you are using an automated annotation tool such as ng-annotate due to potential issues when minifying your code (thanks, #AdityaSingh).
(Edited for clarity and accuracy.)

My Basic Angular App failing me when i'm designing my First Mean stack UI

app.js
var myApp = angular.module('myApp',[]);
myApp.controller('mainCtrl',function($scope){
$scope.name="vignesh";
});
I'm doing a basic app building with MEAN Stack, for most of the parts we use Node API's to connect with MongoDB and user authentication,I'm done with my authentication part in Node.js but while designing routing UI I'm facing this issue
HTML
<!DOCTYPE>
<html ng-app="myApp">
<head>
<title>User Story</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-route.js"></script>
</head>
<body>
<div ng-controller="mainCtrl">{{name}}</div>
<script type="text/javascript" src="/service/authService.js"></script>
<script type="text/javascript" src="/controllers/controllers.js"></script>
<script type="text/javascript" src="/app.js"></script>
</body>
</html>
angular.module('authService',[])
.factory('Auth',function($http,$q,AuthToken){
var authFactory={};
authFactory.login=function(username,password){
return $http.post('/app/login',{
username:username,
password:password
}). sucess(function(data){
AuthToken.setToken(data.token);
return data;
})
}
authFactory.logout=function(){
AuthToken.setToken();
}
authFactory.isLoggedin=function(){
if(AuthToken.getToken())
return true;
else
return false;
}
authFactory.getUser=function(){
if(AuthToken.getToken())
return $http.get('/api/me');
else
return $q.reject({message:"user has no token set"});
}
return authFactory;
})
. factory('AuthToken', function($window){
var authTokenFactory={};
authTokenFactory.getToken=function(){
return $window.localStorage.getItem('token');
}
authTokenFactory.setToken=function(token){
if(token)
$window.localStorage.setItem('token',token);
else
$window.localStorage.removeeItem('token');
}
return authTokenFactory;
})
.factory('AuthInterceptor',function($q,$location,AuthToken){
var interceptorFactory={};
interceptorFactory.request=function(config){
var token=AuthToken.getToken();
if(token){
config.header['x-access-token']=token;
}
return config;
};
interceptorFactory.responseError=function(response){
if(response.status==403)
$location.path('/login');
return $q.reject(response);
}
})
controllers.js
angular.module('mainCtrl', [])
.controller('MainController', function($rootScope,$location,Auth){
var vm = this;
vm.loggedIn = Auth.isLogged();
$rootScope.$on('$routechangeStart',function () {
vm.loggedIn=Auth.isLogged();
Auth.getUser().then(function(data){
vm.user=data.data;
});
});
vm.doLogin= function(){
vm.processing=true;
vm.error='';
Auth.login(vm.loginData.username, vm.loginData.password)
.sucess(function (data) {
// body...
vm.user=data.data;
});
if(data.success)
$location.path('/');
else
vm.erroe=data.message;
}
vm.doLogout=function(){
Auth.logout();
$location.path('/logout');
}
})
error says:
Uncaught SyntaxError: Unexpected token
Uncaught Error: [$injector:modulerr] Failed to instantiate module
myApp due to: Error: [$injector:nomod] Module 'myApp' 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.
You need to initialize you app module correctly.
var myApp = angular.module('myApp', []);
Working Plunkr
Update
As you have different module per each JS file, you need to combine them while using any provider/service that module, As in your case you have used Auth service but the authService module has not injected.
Controllers.js
angular.module('mainCtrl', ['authService']) //injected authService module
.controller('MainController', function($rootScope,$location,Auth){
App.js
var myApp = angular.module('myApp',['mainCtrl']);
myApp.controller('mainCtrl',function($scope){

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

using directives breaks ng-view in angular, how to?

i have a index.html:
<body ng-app="app">
<topmenu></topmenu>
<div ng-view=""></div>
then inside a views folder i have main.html and topmenu.html
there is a route:
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
and a directive
var App = angular.module('app', []);
App.directive('topmenu', function () {
return {
replace: true,
restrict: 'E',
templateUrl: 'views/topmenu.html'
};
});
the problem is when i include the directive.js file and place the <topmenu></topmenu> tag the main.html doesn't load no more
any ideas?
In your directive file you don't need to initialize a variable with your module and dependencies a second time. So this:
var App = angular.module('app', []);
should be removed from that file.
in directive.js
remove this, it will create a new angular module with name 'app'
var App = angular.module('app', []);
if you want get module from angular you can do
var App2 = angular.module('app');
console.log(App === App2) // true
and make sure you already created your 'app' module before you load directive.js,
for example, if you have 2 JS file
<script src="index.js"/>
<script src="directive.js"/>
in index.js do
var App = angular.module('app', []);

Categories