Angularjs controller not found - javascript

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

Related

Using ngroute to redirect unauthorized users in Angular

I am making a web app using Angular for front-end.
If user whose role is teacher trying to access applicant's portal, I want to block them by showing 404.html template. I do not want to redirect the users to www.example.com/404 but rather just let them stay at where they are at www.example.com/teacher but render 404.html template.
I am not sure how I can achieve this using ngroute. Here is the code what I have in app.js:
app.config(['$routeProvider', '$locationProvider', 'CookieProvider',
function ($routeProvider, $locationProvider, CookieProvider) {
var cookieData = CookieProvider.$get().getCookieData();
$routeProvider.when('/applicant', {
templateUrl: '/front-end/public/views/Prescreening/review.html',
controller: 'ReviewCtrl',
resolve:{
"check":function($location, CookieService) {
var cookieData = CookieService.get();
if(cookieData["user_role"] == 'teacher'){
$location.path('/404')
}
}
}
}).when('/404', {
templateUrl: '/404.html'
}).otherwise({
templateUrl: '/404.html'
});
}]);
How can I render 404.thml without redirecting the user to /404 ?
Let's say you have a state like this.
.state('dashboard.users', {
url: '/users/:isAdmin',
templateUrl: 'modules/dashboard/templates/users.html',
controller: 'usersController',
})
Try this.
angular.module(...)
.config( ['$routeProvider', function($routeProvider) {...}] )
.run(function($rootScope, $location) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
// You can pass the user role to the params
// of the state and you will see that on the
// toParams call callback ex. {isAdmin:false}
if(!toParams.isAmin){
toState.templateUrl = "modules/404/templates/404.html";
}
});
})
})
UPDATE
The callback toState actually contains the following
url = url of the current state ex. /user
templateUrl = path to the template ex. path/to/something.html
controller = the controller name of the state ex. usersController
name = the state name ex. dashboard.user
When this line gets executed toState.templateUrl = "modules/404/templates/404.html"; The current template of your state which falls under the <div ui-view></div> will have the 404.html that you desire.
IMPORTANT
You must use ui.router and not ngRouter to make this implementation work.
After some efforts I got it working... Here are the different codes...
I have used bower so please replace with your paths..
Here is the plunk.. I got it working..
https://plnkr.co/edit/dK7n6PmhldJ1p0plWPp2?p=preview
index.js
var app = angular.module('myApp',['ngRoute']);
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/applicant', {
template: 'Applicant!',
controller: function($scope){
alert("Applicant Controller");
}
})
.when('/404', {
templateUrl: '404'
})
.otherwise({
templateUrl : '404.html'
});
}]);
index.html
<html>
<head>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src = "index.js"></script>
</head>
<body ng-app="myApp">
<ng-view></ng-view>
</body>
</html>
404.html
<h1>404 page</h1>

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.

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

Promises getting resolved twice in AngularJS

I am learning to use angularjs with requirejs and angular-ui-router. I created a plunker over here http://plnkr.co/edit/iA8zVQWP3ypRFiZeRDzY?
<div ui-view ></div>
<script data-main="require-config" src="http://requirejs.org/docs/release/2.1.20/r.js"></script>
The startup file index.html has a reference to require-config.js which loads the required third-party javascript libraries, resolves dependencies and bootstraps my module which is in app.js
angular.element().ready(function() {
//bootstrap the app manually
angular.bootstrap(document,['myApp']);
});
I am using ui.router to resolve appropriate states and navigate to the appropriate page
define(['angular', 'story'
], function(angular) {
angular.module('myApp', ['ui.router', 'ui.bootstrap', 'myApp.story'])
.controller('TabController', ['$scope', '$state', function($scope, $state) {
$scope.tabs = [
{route: 'main.story', label : "Promises", active : false},
//more routes here.
];
$scope.go = function(route){
$state.go(route);
};
$scope.active = function(route){
return $state.is(route);
};
$scope.$on("$stateChangeSuccess", function() {
$scope.tabs.forEach(function(tab) {
tab.active = $scope.active(tab.route);
});
});
}])
$stateProvider will route to appropriate state.
config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
abstract: true,
url: '/main',
templateUrl: 'tabs.html',
controller: 'TabController'
})
.state('main.story', {
url: '/story',
templateUrl: 'story.html',
controller: 'storyController'
})
$urlRouterProvider.otherwise('/main/story');
}])
and ui.bootstrap to use tabs provided by bootstrap library.
<tabset>
<tab
ng-repeat="t in tabs"
heading="{{t.label}}"
select="go(t.route)"
active="t.active">
</tab>
</tabset>
This plunker is working with bugs. When I look at the Network in Chrome, the json files ( chapter-1.json and chapter-2.json ) are getting loaded/resolved twice.
I also verified the code without using requireJS and it is working (loading scripts using script tag manually) fine. The promises are getting resolved only once. So, there is some configuration that I am doing incorrectly while using requirejs.
I also verified the files getting loaded twice using $httpProvider.interceptors as well.
How can I resolve this?
In app.js, you are indicating storyController as the controller for your main.story state, but you have an ng-controller="storyController" inside your story.html.
The result is that you are initializing two storyControllers and each one calls .getText() once.
You can solve this by removing the ng-controller from your story.html:
<body>
<div>
{{chapter1}}<br>
{{chapter2}}
</div>
</body>

Unhandled exception in anjular.min.js

I am using angularjs to make a MVC web application...But it gives an error when i'm opening it on internet explorer... But I don't receive an error in other browsers and views are not loading either when click on the links.
This is the error received in Internet Explorer
Unhandled exception at line 33, column 487 in //localhost:18012/Scripts/angular.min.js
0x800a139e - JavaScript runtime error: [$injector:modulerr] http://errors.angularjs.org/1.2.27/$injector/modulerr?p0=sampleApp&p1=Error%3A%20%5B%24injector%3Aunpr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.27%2F%24injector%2Funpr%3Fp0%3D%2524routeProvider%0A%20%20%20at%20Anonymous%20function%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A36%3A196)%0A%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A34%3A273)%0A%20%20%20at%20d%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A34%3A487)%0A%20%20%20at%20Anonymous%20function%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A33%3A386)%0A%20%20%20at%20r%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A7%3A288)%0A%20%20%20at%20e%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A33%3A207)%0A%20%20%20at%20ec%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A36%3A307)%0A%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A18%3A168)%0A%20%20%20at%20dc%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A18%3A380)%0A%20%20%20at%20Wc%20(http%3A%2F%2Flocalhost%3A18012%2FScripts%2Fangular.min.js%3A17%3A415)
I have attached my angular model below. Please help me to solve this.
app.js
//Define an angular module for our app
var sampleApp = angular.module('sampleApp', []);
sampleApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/homeContent.html',
controller: 'AddOrderController'
}).
when('/AddNewOrder', {
templateUrl: 'templates/add_order.html',
controller: 'AddOrderController'
}).
when('/ShowOrders', {
templateUrl: 'templates/show_orders.html',
controller: 'ShowOrdersController'
}).
when('/players', {
templateUrl: 'templates/playersMen.html',
controller: 'ShowOrdersController'
}).
otherwise({
redirectTo: '/'
});
}]);
sampleApp.controller('AddOrderController', function ($scope) {
$scope.message = 'This is Add new order screen';
});
sampleApp.controller('ShowOrdersController', function ($scope) {
$scope.message = 'This is Show orders screen';
});
you are inject $routeProvider
please make sure you loaded:
angular-route.js
cdn:
https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular-route.js
when u loaded,then
add dependency to your app with ngRoute
angular.module('app', ['ngRoute']);
Firstly you have to inject 'ngRoute' in your angular module in the way:
var sampleApp = angular.module('sampleApp', ['ngRoute']);
Another thing is include angular-route.js in your index.html file
This will resolve your problem
Your module is missing ngRoute dependency.Make sure first you add angular-route.min.js
Then added ngRoute dependency inside your app
Your app should look like below.
var sampleApp = angular.module('sampleApp', ['ngRoute']);
Add script reference to html exact after angular.min.js
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular-route.js"></script>
Hope this is helpful to you.
My answer to another case with similar error, if you do not VS2015 US cord that will find it: references the Angular after platformOverrides.js
<body>
<div class="app">
<p id="deviceready" class="event">Connecting to Device</p>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"</script>
<script src="angular/angular.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
</body>

Categories