Controllers across multiple files in Angular JS - javascript

I am trying to modularize the implementation of an angular js project. I am aiming to implement different controllers in their own js files. But that doesnt seem to work.
The following is my config.js ( where the primary module is also defined )
(function() {
var app= angular.module("spa", [
//oob angular modules
//3rd party modules
'ui.router',
'ui.bootstrap'
]);
app.config(['$stateProvider', '$urlRouterProvider', configRoutes]);
//function to config the routes
function configRoutes($stateProvider, $urlRouterProvider) {
$stateProvider
.state('dashboard', {
url: '/',
templateUrl: '../App/Views/dashboard.html',
controller: 'dashboardController',
controllerAs: 'vm'
})
.state('supplier', {
url: '/suppliers',
templateUrl: '../App/Views/supplier.html',
controller: 'supplierController',
controllerAs: 'vm'
})
.state('event', {
url: '/events',
templateUrl: '../App/Views/event.html',
controller: 'eventController',
controllerAs: 'vm'
})
.state('partner', {
url: '/partners',
templateUrl: '../App/Views/partner.html',
controller: 'partnerController',
controllerAs: 'vm'
})
$urlRouterProvider.otherwise('/');
}
app.controller('dashboardController', dashboardController)
function dashboardController() {
alert('dashboard-same function');
}
}());`
the dashboardController triggers fine. But other controllers, written in seperate files dont trigger.
(function () {
'use strict';
var app = angular.module('spa');
app.controller('eventController', eventController);
function eventController() {
alert('event');
}
});
This is the sequence of my references:
<!--External Libs-->
<script src="../Scripts/jquery-1.9.1.js"></script>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-animate.js"></script>
<script src="../Scripts/angular-sanitize.js"></script>
<script src="../Scripts/angular-cookies.js"></script>
<script src="../Scripts/angular-ui-router.js"></script>
<script src="../Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>
<!--Jquery Plugins-->
<!--Custom Libs-->
<script src="../App/Common/config.js"></script>
<!--Controllers-->
<script src="../App/Controllers/event.js"></script>
<script src="../App/Controllers/partner.js"></script>
<script src="../App/Controllers/dashboard.js"></script>
<script src="../App/Controllers/supplier.js"></script>
Thanks in advance

As per my comment, you forgot to execute the wrapping function of eventController.js. It should be
(function () {
'use strict';
var app = angular.module('spa');
app.controller('eventController', eventController);
function eventController() {
alert('event');
}
})();
//^^--------You forgot these
If it doesn't work after said fix, please create a fiddle from your local code instead of the fiddle code to prevent any typo errors and I will take a look.
Also I don't see routes.js in your html, or maybe you meant config.html.

Not completely sure what is going wrong on your side, but here is an example of how I do it:
For example I am using the following setup for modularizing my AngularJS app (v1.3.6):
index.html:
<html>
<head>
<title>Modularize</title>
<!-- load module -->
<script src="app/app.js"></script>
<script src="app/app.constant.js"></script>
<script src="app/app.config.js"></script>
<script src="app/app.run.js"></script>
<!-- load controllers/services/directives/factories -->
<script src="app/controllers/MyController.js"></script>
</head>
<body>
<!-- REST OF THE APP -->
</body>
</html>
app.js
var myapp = angular.module('spa', ['ui.router']);
app.constant.js
myapp.constant(function () {
});
app.config.js
myapp.config(function ($stateProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'app/views/home.html',
controller: 'MyController',
});
});
app.run.js
myApp.run(function () {
});
MyController.js
myapp.controller('MyController', function ($scope) {
});

Related

Cannot inject ui.bootstrap into my module

I'm trying to inject ui.bootstrap into my module, called 'app'. I already included the ui-bootstrap javascript file into my html, but I get below error no matter what I do:
Uncaught Error: [$injector:modulerr]
If I remove any dependencies to ui.bootstrap, the error goes away.
Order of js imports in head tag, all of which load up fine. (checked in Chrome dev tools)
<script src="/Scripts/angular.min.js"></script>
<script src="/Scripts/angular-route.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Scripts/angular-animate.js"></script>
<script src="/Scripts/ui-bootstrap-tpls-1.2.5.min.js"></script>
Current AngularJS version is 1.5.2
app.js
(function () {
'use strict';
var app = angular.module('app', [
// Angular modules
'ngRoute',
'ngAnimate',
'ui.bootstrap',
// Custom modules
// 3rd Party Modules
'ui.router'
]);
app.config(['$locationProvider', '$stateProvider', '$urlRouterProvider', '$modal', function ($locationProvider, $stateProvider, $urlRouterProvider, $modal) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
controller: 'frontpageController',
templateUrl: 'app/views/frontpage.html',
data: {
authorize: false
}
})
.state('login', {
url: '/login',
controller: 'loginController',
templateUrl: 'app/views/login.html',
data: {
authorize: false
}
})
.state('profile', {
url: '/profile/:userId',
controller: 'profileController',
templateUrl: 'app/views/profile.html',
data: {
authorize: true
}
})
.state('error', {
url: '/error',
controller: 'errorController',
templateUrl: 'app/views/404.html',
data: {
authorize: false
}
})
}]);
app.run(function ($rootScope, loginService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var authorize = toState.data.authorize;
if (authorize && typeof $rootScope.currentUser === 'undefined') {
event.preventDefault();
// get me a login modal!
loginService()
}
});
});
})();
You cannot inject services in module config, it only allow providers.
$modal is renamed as $uibModal in last ui-bootstrap too (to rename in your controllers).
So remove '$modal' from your .config inject it only when you use it.
Are you sure ui bootstrap has only one JS file ? Check all folders of ui bootstrap and add if you are missing any other JS files.
You have to add tpls and library for ui bootstrap. For example:
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.2.5/ui-bootstrap-tpls.js"></script>
and
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.2.5/ui-bootstrap.js"></script>
It may be the version of your angular. it says on the site requires AngularJS 1.4.x or higher.

Angular states point to correct controller but not html

I am just setting up a simple Angular app as I've done countless times. I added a home state and a separate state for a note taking app, yet neither states are displaying/injecting the html partials into the ui-view. I think it might be an issue with my ui-router setup, but I cannot find the issue. I console log from my controllers and they trigger correctly, so the states are clearly pointing to the right controllers.
Index
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="bower_components/angular/angular.js"></script>
<script src="node_modules/angular-ui-router/release/angular-ui-router.js"></script>
<script src="app.js"></script>
<script src="factory.js"></script>
<script src="config.js"></script>
</head>
<body ng-app="myApp">
<ui-view></ui-view>
</body>
</html>
config
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateURL: './home.html',
controller: 'homeCtrl'
})
.state('list', {
url: '/list',
templateURL: '/list.html',
controller: 'listCtrl'
})
$urlRouterProvider.otherwise('/home');
});
app.js
'use strict';
var app = angular.module('myApp', ['ui.router']);
app.controller('listCtrl', function($scope, myFactory) {
console.log("list working!");
$scope.items = myFactory.items
$scope.addItem = function() {
$scope.items.unshift($scope.newItem);
$scope.newItem = "";
}
})
app.controller('homeCtrl', function($scope) {
console.log("home working!");
$scope.test = 'test'
})
My home state should load a partial containing:
<div>
<h1>Welcome!</h1>
</div>
Plunker
http://plnkr.co/edit/ngHYDtx0VBe2YPlBeJ3t?p=preview
It has to be
templateUrl: './home.html',
Also, it is not desirable to use relative paths for templates, './home.html' and 'home.html' will be cached internally as two different templates.

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

Error: $injector:modulerr Module Error! AngularJS

I've encountered a problem that I can't seem to fix and I hope someone out there can help me out!
I keep getting this error:
Failed to instantiate module musicApp due to:
{1}
This is the function I'm using:
'use strict';
var angular = angular
.module('angular', ['ngResource', 'ngRoute'])
.config (function ($RouteProvider){
$RouteProvider
.when ('/', {
templateULR: '/templates/list-artists.html'
})
.when ('/add-artist', {
templateUrl: '/add-artist.html'
})
.when ('/artist-details/:id', {
templateUrl: 'artist-details.html'
})
.otherwise ({redirectTo: '/'});
})
.constant ('author', 'Sekret Doge'
This is where I'm calling this function:
'use strict';
angular.controller('ListArtistsController',
function ListArtistsController($scope, artistData) {
$scope.artists = artistData.getAllArtists();
});
And this is my html file, that's supposed to show the information I require:
<div class="jumbotron" ng-controller="ListArtistsController">
<div class="row">
<div ng-repeat="artist in artists">
<div class="col-md-4" text-center>
<h2> {{ artist.name }}</h2>
</div>
</div>
</div>
</div>
I'll even give the script sources because some people are having problems thanks to them:
<script src="lib/jquery-2.1.0.min.js"></script>
<script src="lib/bootstrap.min.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/PageController.js"></script>
<script src="js/controllers/ListArtistsController.js"></script>
<script src="lib/bootstrap.js"></script>
<script src="lib/ui-bootstrap-tpls-0.9.0.min.js"></script>
If there are anymore codes or files missing from this post that you need to look at, just tell me to edit the post!
getAllArtists function:
'use strict';
angular.factory('artistData', function ($resource) {
var resource = $resource('/data/artist/:id', {id: '#id'});
return {
getArtist: function (id) {
return resource.get ({id: id});
},
saveArtist: function (artist) {
artist.id = 999;
resource.save (artist);
},
getAllArtists: function() {
return resource.query();
}
}
});
PageController:
'use strict';
angular.controller('PageController',
function PageController($scope) {
$scope.author = "Sekret Doge";
$scope.date = {
year: 2014,
month: 4,
day: 4
}
}
);
app:
'use strict';
var angular = angular
.module('angular', ['ngResource', 'ngRoute'])
.config (function ($RouteProvider){
$RouteProvider
.when ('/', {
templateUrl: '/templates/list-artists.html'
})
.when ('/add-artist', {
templateUrl: '/add-artist.html'
})
.when ('/artist-details/:id', {
templateUrl: 'artist-details.html'
})
.otherwise ({redirectTo: '/'});
})
.constant ('author', 'Sekret Doge');
Thanks for helping out!
It looks like you aren't loading the ngRoute javascript. It's in a separate file.
http://docs.angularjs.org/api/ngRoute
The following library in the script tag in your HTML needs included in your .js.
lib/ui-bootstrap-tpls-0.9.0.min.js
at the top of app.js add ui.bootstrap.
var angular = angular
.module('angular', ['ngResource', 'ngRoute', 'ui.bootstrap'])

$routeProvider is unknown

I have added the scripts like this
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="Scripts/angular-resource.min.js"></script>
<script src="Scripts/test.js"></script>
and I did this in my test.js
var app = angular.module('MyApp', ['ngRoute']).config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login.html',
controller: 'loginController'
});
$routeProvider.otherwise({ redirectTo: '/login' });
});
app.controller('loginController', function () {
})
I got that the $routeProvider is unknown.
I have read many questions about this and I tried the solutions but nothing works.
help please
notethe angular library is working
I can make binding for example
Try
<div ng-app="MyApp" ng-controller="loginController">{{test}}</div>
then
var app = angular.module('MyApp', ['ngRoute']).config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login.html',
controller: 'loginController'
});
$routeProvider.otherwise({
redirectTo: '/login'
});
});
app.controller('loginController', function ($scope) {
$scope.test = "test me"
})
Since Angular 1.2 - ngRoute module is separated as component, you have to include angular-route.js, then you will have your providers.
https://github.com/angular/angular.js/commit/5599b55b04788c2e327d7551a4a699d75516dd21
https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes-12

Categories