Angular controller not found or defined while doing lazy loading - angularjs

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

Related

When I used ng-include to load html dynamically, the controller of that html is not loaded

I have following scenario
assemblyHeader.js
$scope.AssemblyHeaderDetails = function () {
if {
mixpanelEventTrack('Quote Details Clicked');
var RFQDetailInstance = $modal.open({
templateUrl: 'Scripts/ng/View/QuoteDetailPopup.html',
windowClass: 'QuoteDetail',
controller: 'QuoteDetailPopupController',
resolve: {
AssemblyId: function () { return $scope.AssemblyInfo.assemblyid; },
parentScope: function () {
return $scope;
}
}
});
RFQDetailInstance.result.then(function (result) {
});
}
}
Following is my QuoteDetailPopup.html
<link href="Content/PageCss/requestFormView.css" rel="stylesheet" />
<div>
<div ng-include src="TemplateUrl" >
hello world!!!
</div>
</div>
Following is my controller for html QuoteDetailPopupController.js
(function () {
'use strict';
var controllerId = 'QuoteDetailPopupController';
angular.module('CalcQouteModule').controller(controllerId,
['$scope', 'DataConstants', '$filter', 'MessageConstant', '$modalInstance', 'parentScope', '$modal', 'urlConstant', '$timeout', QuoteDetailPopupController]);
function QuoteDetailPopupController($scope, DataConstants, $filter, MessageConstant, $modalInstance, parentScope, $modal, urlConstant, $timeout) {
$scope.TemplateUrl = 'Scripts/ng/View/requestFormView.html';
}
}());
The problem is when modal popup opens it renders HTML page but didn't render the controller of requestFormView.html so the controls on HTML are not loaded properly.
For requestFormView.html the controller name is requestFormController.js
Following popup is opened when I clicked.
How can I load controller?
Add controller file in index.html and in app.js when you hit the url mention controller name over there. Hope this will help you.

Application url is ..index.html#/signup instead of ..index.html/#/signup

I'm building an AngularJS(1.4.7) app. My signup url supposed to be ....index.html/#/signup. But when I click signup link it shows ....index.html#/signup. And my signup view is not loading when I click signup button.
My app.js file: http://pastebin.com/ZHZkUV7m
My index.html file: http://pastebin.com/SAkyYAWu
My indexController:
'use strict'
app.controller('indexController', ['$scope', '$location', 'authService', function ($scope, $location, authService) {
$scope.logot = function () {
authService.logot();
$location.path('/home');
};
$scope.authentication = authService.authentication;
}]);
Actually I'm playing with this blog post: http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/
Here's a very minimal, yet working example of to implement ngRoute:
http://plnkr.co/edit/dxo3ZUJIWLeFw9HXF80w
JavaScript
angular.module('testModule', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/foo', {
template: '<p>Foo</p>'
})
.when('/bar', {
template: '<p>Bar</p>'
})
.when('/baz', {
template: '<p>Baz</p>'
})
.otherwise({
redirectTo: '/index.html'
});
}]);
HTML
<body>
Go to foo<br>
Go to bar<br>
Go to baz<br>
<div ng-view></div>
</body>

Angular lazy loading controller not found exception

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.

how to send the data of a ng-controller to another jsp page when click on send button?

Here i will add the product data from response of http for myctrl then when i click on checkout i have to bind all this information and send it to another jsp page in that page i have to get the response data.How can i achieve it by using angularjs. please help me out
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-repeat="x in names">
<div>Product Name : {{x.itemname}}</div>
<div>Qty : {{x.itemQty}}</div>
<div>Price : {{x.itemQty}}</div>
<div>Total : {{x.itemQty}}</div>
</div>
<div><button ng-click="checkOut()" >CheckOut</button></div>
</div>
<script>
angular.module("MyApp",[])
.controller("MyCtrl", ['$scope', '$http', function($scope, $http) {
$http.get('responseData.html').success(function(response) {
$scope.names= response;
});
}]);
</script>
Whenever you want to persist the any object/value on client side, I'd suggest you to don't redirect the user to other page.
Instead do create a SPA, add route based view to your application. For implementing such a powerful SAP you could use angular-route API designed by angular team OR you could also use ui.router which is developed by angular-ui team. Suppose you choose angular-route here then, show different view on different routes, you need to configure you route in angular config phase using $routeProvider & then load view and controller for partial view. In your case it would be confirmation submit page on click of button.
You could have one wrapper div on your ng-view directive and then give mainCtrl controller to it. That will act as a sharing component amongest your various views.
HTML
Controller
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1.html',
controller: 'CustomerDetailsController'
})
.when('/view2', {
templateUrl: 'view2.html',
controller: 'form2Ctrl'
})
.otherwise({
redirectTo: '/view1'
});
});
app.controller('mainCtrl', function($scope) {
$scope.form = {}; //this is global and thats why it can be available on any view
});
app.controller('CustomerDetailsController', function($scope,$location) {
$scope.submit = function(){
if($scope.form1.$valid)
$location.path('/view2');
};
});
app.controller('form2Ctrl', function($scope,$location) {
//this controller contain the data which will you get from
});
Preferable approach for sharing a data would be using singleton service/factory in your application.
HTML
<div class="forms">
<ng-view></ng-view>
</div>
app.service('sharedData', function() {
var sharedData = this;
sharedData.myData = {};
});
app.controller('CustomerDetailsController', function($scope,$location, sharedData) {
$scope.submit = function(){
sharedData.myData.formData = $scope.form1Data; //form1Data will have form1Data
if($scope.form1.$valid)
$location.path('/view2');
};
});
app.controller('form2Ctrl', function($scope,$location, sharedData) {
console.log(sharedData); //this will have the data shared from the CustomerDetailsController
});
For more info Refer this SO Question, Thanks.

Angular factory always called twice

I am calling a REST service from angular and it always calls the factory twice. Here is the factory code.
app.factory('dataFactory', ['$http', function ($http) {
var urlBase = '/api';
var dataFactory = {};
dataFactory.getMyItems = function () {
return $http.get(urlBase + '/MyItems');
};
return dataFactory;
} ]);
It's called from the controller here
app.controller('MyItemsController', ['$scope', 'dataFactory',
function ($scope, dataFactory) {
$scope.myItems;
getItems();
function getItems() {
dataFactory.getMyItems()
.success(function (itemsData) {
$scope.myItems = itemsData;
})
.error(function (error) {
$scope.status = 'Unable to load items data: ' + error.message;
});
}
}
]);
I had the same problem as yours where the controller in general was called twice; hence, the factory will be called twice.
But after looking at this solution:
Combating AngularJS executing controller twice
Step 1:
Make sure you are adding the service and controller in your (main layout view) only once.
Example:
index.html
<script src="../MyItemsController.js"></script>
<script src="../MyItemsService.js"></script>
If the problem still persists after doing step 1 go to step 2
Step 2:
There are two ways to do it:-
1. Either keep the controller in your view (ng-controller), and remove it from your config route like this:
route config (usually, app.js):
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/',
{
templateUrl: 'pages/home.html'
//Remove controller from here
});
}]);
home.html
<!-- Add the ng-controller in your view -->
<div ng-controller="MyItemsController">
<!-- Your stuff -->
</div>
2. Or keep the controller in your config route, and remove ng-controller
from view like this:
route config (usually, app.js):
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/',
{
templateUrl: 'pages/home.html',
controller: 'MyItemsController' //Add the controller here
});
}]);
home.html
<!-- Remove the ng-controller in your view -->
<div>
<!-- Your stuff -->
</div>
Note: The above solution works with ui router as well.

Resources