I have tried to lazy load a controller in angularjs app, but got stuck with some problems i.e. view loads after the controller but in console throws exception controller not found.
Here i have attched the sample code.
index.html:
Click here
<div data-ng-view>
</div>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/ocLazyLoad.min.js"></script>
<script src="js/app.js"></script>
<script src="js/cofig.js"></script>
</body>
</html>
app.js:
var testapp = angular.module('test',['ngRoute','oc.lazyLoad']);
config.js:
testapp.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/test1',{
templateUrl: 'partials/test.html',
controller: 'testController',
resolve: {
lazy: ['$ocLazyLoad',function($ocLazyLoad) {
$ocLazyLoad.load([{
name: 'test',
files: ['js/testController.js']
}]);
}]
}
})
}]);
console.log error:-
enter code here`Error: [ng:areq] http://errors.angularjs.org/1.3.7/ng/areq?p0=testController&p1=not%20aNaNunction%2C%20got%20undefined
This issue is because of you are loading the controllers lazily. When you load the controller lazily, this will not be available to the main module. So you have to register those controllers.
By attaching the controller provider and provide to the main module, we can use it later to register controller.
In app config,
SampleApp.registerController = $controllerProvider.register;
SampleApp.$register = $provide;
To register controller:
var SampleApp = angular.module('SampleApp');
SampleApp.$register.factory('landingService', ['$http', '$rootScope', function ($http, $rootScope) {
debugger
return {
GetQuestions: function () {
return $http({
url: ""
});
}
}
}]);
SampleApp.registerController('landingController',
['$scope', '$http', 'landingService', function (scope, http, landingService) {
scope.GetQuestions = function () {
landingService.GetQuestions().success(function (data) {
}).
error(function (data) {
});
}
}]);
The following tutorial will help you to implement the Angular Lazy Loading using RequireJS with OcLazyLoad.
Angular Lazy Load implementation
You should add the lazyLoad service to your config injection:
testapp.config(['$routeProvider', '$ocLazyLoad', function($routeProvider, $ocLazyLoad){
$routeProvider.when('/test1',{
templateUrl: 'partials/test.html',
controller: 'testController',
resolve: {
lazy: ['$ocLazyLoad',function($ocLazyLoad) {
$ocLazyLoad.load([{
name: 'test',
files: ['js/testController.js']
}]);
.......
[UPDATED]
I guess you defined your test controller in the js file and want to lazy load the controller. But your code is not correct. Try this:
testapp.config(['$routeProvider', '$ocLazyLoad', function($routeProvider, $ocLazyLoad){
$routeProvider.when('/test1',{
templateUrl: 'partials/test.html',
controller: 'testController',
resolve: {
lazyTestCtrl: ['$ocLazyLoad',function($ocLazyLoad) {
return $ocLazyLoad.load('js/testController.js');
}]
}
You can get the doc from official site.
Related
I have created a web api project and after that i am going to create single page application but getting some error so i am posting my code below:
My angularjs code:
var app = angular.module('myApp', ['ngRoute']);
app.config('$routeProvider', function ($routeProvider) {
$routeProvider
.when('/',{
templateUrl: 'tpl/users.html',
controller: 'myController'
})
.when('/addusers', {
templateUrl: 'tpl/addusers.html',
controller: 'addusers'
})
.when('/admin',{
templateUrl: 'tpl/admin.html',
controller: 'admin'
});
});
app.controller('myController', function ($scope) {
$scope.message = 'Home';
});
app.controller('admin', function ($scope) {
$scope.message = 'Admin';
});
app.controller('addusers', function ($scope) {
$scope.message = 'addusers';
});
and my html page:
<html ng-app="myApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="app/app.js"></script>
</head>
<body ng-controller="myController">
Home
Admin
Add Users
<br />
<div ng-view> </div>
</body>
</html>
and getting below angularjs error:
Error: [$injector:modulerr] http://errors.angularjs.org/1.2.25/$injector/modulerr?p0=myApp&p1=%5Bng%3Aareq%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.25%2Fng%2Fareq%3Fp0%3Dfn%26p1%3Dnot%2520a%2520function%252C%2520got%2520string%0AD%2F%3C%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A6%3A450%0ADb%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A19%3A106%0AWa%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A19%3A193%0Asc%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A32%3A423%0Ad%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A34%3A398%0Ae%2F%3C%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A33%3A386%0Ar%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A7%3A288%0Ae%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A33%3A207%0Agc%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A36%3A309%0Afc%2Fc%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A18%3A170%0Afc%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A18%3A387%0AXc%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A17%3A415%0A%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A214%3A469%0Aa%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A145%3A67%0Aoe%2Fc%2F%3C%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A31%3A223%0Ar%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A7%3A288%0Aoe%2Fc%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A31%3A207%0AEventListener.handleEvent*sb%3C%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A143%3A241%0Aa%2F%3C%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A150%3A402%0Ar%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A7%3A288%0Aa%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A149%3A381%0AS.prototype%5Bc%5D%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A154%3A57%0AS.prototype.ready%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A145%3A122%0A%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A214%3A447%0A%40http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.25%2Fangular.min.js%3A6%3A2%0A
Your controller definitions (dependency injection parts) is wrong.
You can follow the john papa's style guide for angular
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/',{
templateUrl: 'tpl/users.html',
controller: 'myController'
}).when('/addusers', {
templateUrl: 'tpl/addusers.html',
controller: 'addusers'
}).when('/admin',{
templateUrl: 'tpl/admin.html',
controller: 'admin'
});
}]);
app.controller('myController', ['$scope', function ($scope) {
$scope.message = 'Home';
}]);
app.controller('admin', ['$scope', function ($scope) {
$scope.message = 'Admin';
}]);
app.controller('addusers', ['$scope', function ($scope) {
$scope.message = 'addusers';
}]);
I am working on a SPA in angular as well and got the same error very recently,
This is something that i found to happen when i was using ngRoute. ngRoute works but it seems very messy to me and kept giving me this error and some other ones.
I was probably just using it wrong, but i recommend you switch to "UI-Router"
It should clean up the way you do routing and make it easier to handle objects throughout your project.
You're using the config wrong. You don't need to use '$routeProvider' as a parameter.
Incorrect
app.config('$routeProvider', function ($routeProvider) {
});
Correct
app.config(function ($routeProvider) {
});
Also, Angular no longer uses ngRoute out of the box. It's a separate file you need to include (note the version):
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.js
Context: I just got started with AngularJS, starting from a clean generator-angular-fullstack build. As part of the install I went with UI router.
I've set up server API endpoints and tested them in the browser. They all check out.
I'm trying to do a minimal http.post request to call those API endpoints. Via Yeoman I've pre-generated a new route 'signIn' in client/app/signIn (which includes signIn.html, signIn.js, signIn.controller.js, signIn.controller.spec.js, signIn.scss).
Here is what I'm working from:
signIn.html
<script>
var MainCtrl = function($scope, $http) {
$http.post('/api/auth/signin', {auth_token: '5'}).success(function(response) {
$scope.response = response;
});
};
</script>
<body ng-controller="MainCtrl">
<section ui-view>Response: {{response}}</section>
</body>
For completeness (still untouched:)
signIn.js
'use strict';
angular.module('orbitApp')
.config(function ($stateProvider) {
$stateProvider
.state('signIn', {
url: '/signIn',
template: '<sign-in></sign-in>'
});
});
signIn.controller.js
'use strict';
(function(){
class SignInComponent {
constructor() {
this.message = 'Hello';
}
}
angular.module('orbitApp')
.component('signIn', {
templateUrl: 'app/signIn/signIn.html',
controller: SignInComponent
});
})();
I've tried a number of variations on the signIn.html script, no luck so far. I'd like to find the 'native' way to do it, so I'd rather not use jquery. Any advice would be appreciated!
I don't understand exactly what you're trying to do but I hope this code will help you :
signIn.html
<body>
<section ui-view>Response: {{response}}</section>
<a class="btn btn-info" href="#" ng-click="callingPostFct()" role="button">Trigger http post using button as example</a>
</body>
signIn.js
'use strict';
angular.module('orbitApp')
.config(function ($stateProvider) {
$stateProvider
.state('signIn', {
url: '/signIn',
template: '<sign-in></sign-in>'
});
});
signIn.controller.js
'use strict';
(function(){
class SignInComponent {
constructor($scope, $http) {
$scope.callingPostFct = function() {
$http.post('/api/auth/signin', {
//do anything you want with your api endpoint here :
auth_token: '5'
}).success(function(response) {
console.log('post successfully worked !');
$scope.response = response;
});
};
}
}
angular.module('orbitApp')
.component('signIn', {
templateUrl: 'app/signIn/signIn.html',
controller: SignInComponent
});
})();
Note :
Don't put ng-controller="" in your html files because they are already called by the generator and they will be called twice or even more which could produce some trouble in your app and reduce performance also.
In most of case, when you're trying to use <script> tag, you can do it in the controller.
I am working with IONIC Framework (Angularjs)
I am receiving below error,
463788 error Error: [ng:areq] http://errors.angularjs.org/1.4.3/ng/areq?p0=PaymentCtrl&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at http://localhost:8100/lib/ionic/js/angular/angular.min.js:6:416
at Sb (http://localhost:8100/lib/ionic/js/angular/angular.min.js:22:18)
at Qa (http://localhost:8100/lib/ionic/js/angular/angular.min.js:22:105)
at http://localhost:8100/lib/ionic/js/angular/angular.min.js:79:497
at I.appendViewElement (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:4463)
at Object.O.render (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:16:17590)
at Object.O.init (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:16:16825)
at I.render (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:3419)
at I.register (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:3150)
Here is my code for controller.
define(['ionic', 'ionicAngular', 'angular',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular) {
'use strict';
console.log('Payment controller ');
var PaymentCtrl = function ($scope, PaymentSvc,$state, $ionicLoading) {
/*$scope.phoneNumberVerification = function() { $state,$ionicPopup,
console.log('PhoneNumber controller added1 ');
$ionicLoading.hide();
$state.go('tab.eateries');
};*/
// When button is clicked, the popup will be shown...
};
return PaymentCtrl;
});
Serveics.js
define(['ionic', 'ionicAngular', 'angular',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular) {
'use strict';
//console.log('service modules');
var PaymentSvc = function(){
console.log('serverices call');//var svc = this;
}
return PaymentSvc;
});
// });*/
payment.js
define(['ionic', 'ionicAngular', 'angular',
'./modules/payment/controllers/paymentctrl',
'./modules/payment/services/services',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular,
paymentCtrl,
paymentSvc) {
'use strict';
console.log('payment.js modules');
var payment = angular.module('payment', ['ionic'])
.controller('PaymentCtrl', paymentCtrl)
.service('PaymentSvc',paymentSvc);
return payment;
});
No need to inject ['angular','ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter']. Ionic automatically inject angular decencies when you inject ['ionic']
Just write your controller directly
angular.module('starter', ['ionic']).controller('PayCtrl',function ($scope,$state,$ionicLoading,PaymentSvc){
//starter is the app name come from ng-app="starter"
$ionicLoading.show();
$scope.phoneNumberVerification = function(){
console.log('PhoneNumber controller added1');
$ionicLoading.hide();
$state.go('tab.eateries');
};
});
I advise you to organize your javascript project files to in 3 files:
app.js which contains
angular.module('starter', ['ionic', 'starter.controllers','starter.services'])..config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
}).state('app.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/home.html',
controller : 'HomeCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/home');
});
controller.js which contains your controllers
angular.module('starter.controllers', []).controller('AppCtrl', function('PayCtrl',function ($scope,$state,$ionicLoading,PaymentSvc){
$ionicLoading.show();
$scope.phoneNumberVerification = function(){
console.log('PhoneNumber controller added1');
$ionicLoading.hide();
$state.go('tab.eateries');
};
});
service.js which contains you connections to server
angular.module('starter.services', []).factory('PaymentSvc',function($http,$q){
});
it is an injection error. for example, if you inject ['a','b','c'] you must have it in your function in the same order and amount: function(a,b,c). in your case, you have more parameters in the injection than the parameters in your controller function.
Hi iam using Angular with Require.
Require is managing my dependency sequence. Using lazy loading for loading controller and i was able to load my first home controller but when i wanted to navigate to dashboard controller then iam getting error dashboard controller is not found. hereis code
main.html
<body ng-app >
<div id="ViewPort" ng-view> </div>
</body>
shell.js
define(['mngRoute', 'mngSanitize'], function (ngRoute, ngSantize) {
var CMSapp = angular.module('CMS', ['ngRoute', 'ngSanitize']);
CMSapp.config(function ($routeProvider, $httpProvider) {
console.log($httpProvider);
$routeProvider
// route for the home page
.when('/', { templateUrl: 'App/Partials/home.html', resolve: loader(['Home']) })
.when('/Dashboard', { templateUrl: 'App/Partials/Dashboard.html', resolve: loader(['Dashboard']) })
});
CMSapp.run(function () {
console.log('shell loaded');
console.log(CMSapp);
});
return CMSapp;
Home Controller.js
define(function () {
angular.module('CMS').controller('HomeController', ["$scope", "$http", 'MainService', function ($scope, $http, mainService) {
$scope.message = 'Homess';
$scope.InitializeController = function ()
{
console.log(mainService);
mainService.initializeApplication($scope.initializeApplicationComplete, $scope.initializeApplicationError);
}
$scope.initializeApplicationComplete = function (response) {
console.log('in default initializeApplicationComplete');
}
$scope.initializeApplicationError = function (response) {
console.log('in default intialize error');
}
}]);
});
Home.html
<div data-ng-controller="HomeController" ng-init="InitializeController()">
<span>{{message}}</span>
Dashboardcontroller and dashboard.html are same only difference is the name
define(function () {
angular.module('CMS').controller('DashboardController', ["$scope", "$http", 'MainService', function ($scope, $http, mainService) {
$scope.message = 'Dashboard';
$scope.InitializeController = function ()
{
console.log(mainService);
}
}]);
});
Dasboard html
<div data-ng-controller="DashboardController" ng-init="InitializeController()">
<span>{{message}}</span>
i was able to load home and able to bind with model, but this not in dashboard when i entered localhost:8999/Main.html#/Dashboard in url it gives error.
See the chrome console Full console
Angular, Route, Dasboardcontroller.js homecontroller.js shell.js are loaded successfuly no error in console only error is Dasboard controller is not a function, got defined
When you use ng-app, Angular will search for a module called app. If you want to specify a custom module, you need to tell it: ng-app="CMS"
I hope this works! :)
<body ng-app >
should be
<body ng-app="CMS">
because in your code you declare your module as so.
angular.module('CMS'
Chrome console image console2
You can see my app is loaded bootstrapped and controllers are registered as well
I want to load controllers on the fly when needed rather than loading them in one go. So, for the I've implemented dynamic approach which works fine without any error. It also works well with Ui-Router.
But the problem is in Index.html page. I want to put global (super parent) controller name "appCtrl". As this appCtrl should be initialized when I run my app. For that I need to write like ng-controller="appCtrl" or ng-controller="appCtrl as vm" at body tag.
But when I do it, it gives error that appCtrl is a function, got undefined. I tried sever ways but still unable to identify exact error. I have working on this issue since two to three days but still not able to identify it.
I have made this plunker.
look at body tag of index.html.
main.js
require.config({
paths: {
"angular": "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular",
"ui-router": "//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router"
},
shim: {
"angular": {
exports: 'angular'
},
"ui-router": {
deps: ['angular']
}
}
});
define(
['angular',
'app',
'controllers/appCtrl'],
function (angluar, app) {
angular.bootstrap(document, ['MyApp'])
});
app.js
define([
'angular',
'ui-router'
], function (angular) {
var app = angular.module('MyApp', ['ui.router']);
function lazy () {
var self = this;
this.resolve = function (controller) {
return {
ctrl: ['$q', function ($q) {
var defer = $q.defer();
require(['controllers/' + controller], function (ctrl) {
app.register.controller(controller, ctrl);
defer.resolve();
});
return defer.promise;
}]
};
};
this.$get = function (){
return self;
};
}
function config ($stateProvider, $urlRouterProvider,
$controllerProvider, $compileProvider,
$filterProvider, $provide, lazyProvider) {
$stateProvider
.state("home", {
url: "/",
controller: 'homeCtrl',
controllerAs: 'vm',
templateUrl: 'views/homeView.html',
resolve: lazyProvider.resolve('homeCtrl')
});
app.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service,
constant: $provide.constant
};
}
app.provider('lazy', lazy);
app.config(config);
return app;
});
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.17/require.js" data-main="main.js"></script>
</head>
<body ng-controller="appCtrl as vm"> // I want this to work correctly but it is not getting loaded dynamically. I don't know why. Help me to resolve it.
<a ui-sref="home">go home</a>
<ui-view></ui-view>
{{vm.appVar}}
</body>
</html>
You are actually missing the controller statement in your controller code.
Use the following code
define(['app'], function (app){ //Updated Line
console.log('app controller loaded');
app.controller('appCtrl',ctrl); //New Line added
ctrl.$inject = ['$http'];
function ctrl ($http) {
this.appVar = 'hi from appCtrl';
};
return ctrl;
});
See the plunker