Cannot inject ui.bootstrap into my module - javascript

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.

Related

Unknown provider: $stateProvider

I can't really get my head around why this markup doesn't recognize my $stateProvider?
Uncaught Error: [$injector:modulerr] Failed to instantiate module app due
to: Error: [$injector:unpr] Unknown provider: $stateProvider
Simple module:
(function () {
'use strict';
// get modules we need for the app
angular.module('app', ['ngRoute'])
.config(config);
config.$inject = ['$stateProvider']
function config($stateProvider) {
console.log('works'); // actually doesn't
};
})();
I've tried various other styles
eg loading them straight in the config
.config(['$stateProvider'], function ($stateProvider) {
// not working this way either.
});
You are using ngRoute in that way you have to use the $routeProvider. The $stateProvider is based on ui-router. Please check this runnable fiddle and switch to $routeProver or use ui-router in combination with $stateProvier.
ngRoute configuration
This is a runnable fiddle of ngRoute implementation.
/* App Module */
angular.module('demoApp', ['ngRoute'])
.config(['$routeProvider', function( $routeProvider) {
// Define routes
$routeProvider.when('/homepage', {
templateUrl: 'partial/homepage.html',
controller: HomePageCtrl
}).when('/users', {
templateUrl: 'partial/users.html',
controller: UsersListCtrl
}).when('/contacts',{
templateUrl: 'partial/contacts.html',
controller: ContactPageCtrl
}).otherwise({
redirectTo: 'homepage'
});
}
]);
ui-router configuration
This is a runnable fiddle of ui-route implementation.
var myApp = angular.module("myApp",["ui.router"])
.config(function ($stateProvider, $urlRouterProvider){
$stateProvider.state("state1", {
url: "#",
template: "<p>State 1</p>",
controller: "Ctrl1"
}).state("state2", {
url: "#",
template: "<p>State 2</p>",
controller: "Ctrl2"
});
});

AngularJS and RequireJS add controller to view

I have a problem with adding a Angular controller to my HTML view. The angular way of doing this is: ng-controller="<controller>". But because I am using RequireJs I have to do this in a different way. I have to add a sub page to every controller and view:
define(['app', 'login/LoginController'], function (app, LoginController) {
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: "modules/" + 'login/login.html',
controller: LoginController
});
});
app.controller('LoginController', LoginController);
});
This way I can define my where my controller is and where my view is.
Problem
Now I have a header.html in which I want to include a menu.html. this can be done via: ng-include="'modules/menu/menu.html'". This works fine. But how can I add a controller to this menu.html?
I have tried: ng-controller="MenuController" but then I get the error: 'Error: [ng:areq] Argument 'MenuController' is not a function, got undefined'. So I do not know how I should add a controller to my menu.html with RequireJS.
MenuController
my MenuController looks as follows:
define(['$'], function ($) {
'use strict';
var MenuController = function ($location, menu, $scope) {
$scope.info="testing123";
};
return MenuController;
});
Anyone knows how I should do this?
You can for example use multiple views in the same controllerwith $stateProvider:
app.config(function ($stateProvider, $locationProvider) {
$stateProvider
.state('login', {
url: '/',
views: {
'menu': {
templateUrl: 'modules/menu/menu.html',
controller: MenuController
},
'login': {
templateUrl: 'modules/login/login.html'
controller: LoginController
}
}
});
});
Then in your template to call them you just need to do something like:
<div ui-view="menu"></div>
<div ui-view="login"></div>
You can see more info on github ui-router.

Can't lazy load controllers in angular with oc.lazyLoad - controller not found

I want to use lazy loading in my Angular project:
This is the relevant app.js code:
var app = angular.module('eva', ['ui.router',
'controllers', 'oc.lazyLoad']);
app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', '$locationProvider', '$ocLazyLoadProvider',
function($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, $ocLazyLoadProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
$urlRouterProvider.otherwise("/");
$locationProvider.hashPrefix('!');
$stateProvider.state('challenge', {
url: '/challenges',
templateUrl: 'views/Challenges.html',
controller: 'ChallengeCtrl',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}],
resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load('js/controllers/ChallengeController.js');
}]
}
This is my controller definition code:
angular.module('eva').controller('ChallengeCtrl', ['$scope', 'auth','$translate', 'challengeFactory', 'userFactory', 'userService',
function($scope, auth, $translate, challengeFactory, userFactory, userService) {
I am not loading the challengecontroller.js file in the index.html file.
I include oclazyload just before app.js in the index.html file:
<script type="text/javascript" src="js/lib/oclazyload/dist/ocLazyLoad.js"></script>
<script type="text/javascript" src="js/app.js"></script>
I get this error now when I run the app:
Error: [ng:areq] http://errors.angularjs.org/1.4.7/ng/areq?p0=ChallengeCtrl&p1=not%20a%20function%2C%20got%20undefined
I tried many things for lazy loading, none of them worked. Now I just followed the example on Example
I really am in a pickle here, and I have no clue what to do to get the lazy loading working. I rather not work with requirejs.
angular config is just a function, any dependencies should be already $inject before you call this config. you may include it in <script> tag and add it to app = angular.module['app', ['depend1'])
so you change it and try it again.
app.config(function($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider, $ocLazyLoadProvider) {
btw: open your Browser Dev-Tools, to check whether this file js/controllers/ChallengeController.js is loadead correctly

Using ocLazyLoad to lazy load a controller with $stateProvider

I'm having issues using oclazyload with $stateProvider.
I have specified that the controller .js should be loaded in the router config, and it does,' but it's not available to use as an ng-controller attribute in the file loaded in templateURL.
ui-route config:
core
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]
)
.config(
[ '$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
console.info('Routing ...');
$urlRouterProvider
.otherwise('/app/dashboard');
$stateProvider
.state('app', {
abstract: true,
url: '/app',
templateUrl: 'templates/app.html',
})
.state('app.orders', {
abstract: true,
url: '/orders',
templateUrl: 'templates/orders/orders.html',
})
.state('app.orders.index', {
url: '/index',
templateUrl: 'templates/orders/index.html',
resolve: {
deps: ['$ocLazyLoad',
function( $ocLazyLoad ){
console.info('Path ot order controller in route config',Momento.paths.js + 'controllers/orders/index.js');
return $ocLazyLoad.load([
Momento.paths.js + 'controllers/orders/index.js'
])
}
]
}
})
}
]
)
;
And my templateURL file starts:
<div class="" id="" ng-controller="OrdersIndexController">...</div>
But when it loads, console throws the error:
<info>orders/index controller loaded controllers/orders/index.js:3
<info>Now I've finished loading the controller/order/index.js config/ui-router.js:69
<info>orders template loaded VM30437:1 (<-- this is the app.orders abstract template with ui-view directive ready for app.orders.index view)
<error>Error: [ng:areq] Argument 'OrdersIndexController' is not a function, got undefined
... <trace>
So the file is loaded correctly by lazyload, confirmed by console output above and network tab in developer tools, but it's not available in the templateURL to use as controller? Does it need to be aliased either in router config using controller:'' key or in template? Does it need to be specifically attached to the (only) module in this app?
What am I missing?
PS: confirming that the name of the controller is in fact OrdersIndexController:
core
.controller('OrdersIndexController', [
'Model', '$scope', '$window',
function( Model, $scope, $window){
console.info("OrdersIndexController fired");
}
]);
You have to register your controller with
angular.module("myApp").controller
Working
angular.module("myApp").controller('HomePageController', ['$scope', function ($scope) {
console.log("HomePageController loaded");
}]);
Not working
var myApp = angular.module("myApp")
myApp.controller('HomePageController', ['$scope', function ($scope) {
console.log("HomePageController loaded");
}]);
Inside the function function($ocLazyLoad){} you must to declare the name of module that contains the controller and the name of file "to lazy load"
function( $ocLazyLoad ){
return $ocLazyLoad.load(
{
name: 'module.name',
files: ['files']
}
);
}
If you use the current documented way for ocLazyLoad 1.0 -> With your router
...
resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load('js/AppCtrl.js');
}]
}
then in js/AppCtrl.js
You have something like this:
angular.module("myApp").controller('DynamicNew1Ctrl', ['$scope', function($scope) {
$scope.name = "Scoped variable";
console.log("Controller Initialized");
}]);
Note that with angular.module("myApp") you are attaching the new controller to an existing module, in this case the mainApp, so any of new dynamic controllers can use the app dependencies.
but you can define a new module an inject your dependencies, as described here, the later is used commonly when you estructure your app with a plugin architecture and you want to isolate the dynamic modules so they only have access to some especific dependencies

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

Categories