So I am asking question after investing almost 2 hours to find the root cause of my problem.
My Index.html
<!doctype html>
<html>
<head>
<title>Single Page Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="myApp.js"></script>
</head>
<body ng-app="myApp">
<ul>
<li>Home</li>
<li>Student</li>
<li>Courses</li>
</ul>
<div ng-view=""></div>
</body>
</html>
My myApp.js
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'HomeCntrl'
});
$routeProvider.when('/student', {
templateUrl : 'student.html',
controller : 'StudentCntrl'
});
$routeProvider.when('/courses', {
templateUrl : 'courses.html',
controller : 'CoursesCntrl'
});
}]);
app.controller('HomeCntrl', ['$scope', function($scope){
alert("HomeCntrl");
$scope.message = "Welcome to home page";
}]);
app.controller('StudentCntrl', ['$scope', function($scope){
alert("StudentCntrl");
$scope.message = "Welcome to Student page";
}]);
app.controller('CoursesCntrl', ['$scope', function($scope){
alert("CoursesCntrl");
$scope.message = "Welcome to Courses Page";
}]);
And some other htmls with code
<h1>Home</h1>
{{message}}
<h1>Student Page</h1>
{{message}}
<h1>Courses Page</h1>
{{message}}
I am using brackets to run this app. Let it be default hit or click over any link its always giving alert("HomeCntrl") only.
Note- The same code is running in plunker very well.
WHAT AM I DOING WRONG??
Edit 1- Added screenshot of one click
I clicked on Courses. But the popup I got is 'HomeCntrl'
Edit 2 - Added my plunker link
Plunker Link
http://plnkr.co/edit/HehCAD4afiN4xD828YYT?p=preview
Edit 3 - Adding Screenshot of console
clicked on Student link
You dont need to do an inject on your config and you also dont need to repeat $routeProvider. Change it to this.
HTML:
<!doctype html>
<html>
<head>
<title>Single Page Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="myApp.js"></script>
</head>
<body ng-app="myApp" ng-controller="Universal as universal">
<ul>
<li><span ng-click="universal.goTo('/')">Home</span></li>
<li><span ng-click="universal.goTo('/student')">Students</span></li>
<li><span ng-click="universal.goTo('/courses')">Courses</span></li>
</ul>
<div ng-view=""></div>
</body>
</html>
Code:
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'HomeCntrl'
})
.when('/student', {
templateUrl : 'student.html',
controller : 'StudentCntrl'
})
.when('/courses', {
templateUrl : 'courses.html',
controller : 'CoursesCntrl'
});
});
app.controller('Universal', ['$scope', '$location', function($scope, $location){
// alert("HomeCntrl");
var scope = this;
scope.goTo = function(where){
$location.path(where)
}
}]);
app.controller('HomeCntrl', ['$scope', function($scope){
// alert("HomeCntrl");
$scope.message = "Welcome to home page";
}]);
app.controller('StudentCntrl', ['$scope', function($scope){
alert("StudentCntrl");
$scope.message = "Welcome to Student page";
}]);
app.controller('CoursesCntrl', ['$scope', function($scope){
alert("CoursesCntrl");
$scope.message = "Welcome to Courses Page";
}]);
What I did here was add a universal controller that you can use to handle routing. Make sure to inject $location so that it can navigate. When using angular routing you want to avoid using hrefs and use angularjs native routing. This code will work for you. Here is the Plunkr example I made.
Your latest screenshot shows what the problem is.
Look at the URL:
127.0.0.1:63688/index.html#!/#%2Fstudent
This means that the part #/student or #/courses is being blindly appended to the existing URL 127.0.0.1:63688/index.html#!/. Since the required #/ is there after the index.html you get shown your 'HomeCntrl'.
To get shown 'StudentCntrl' you need the URL to be:
127.0.0.1:63688/index.html#/student
On sites like Plunker, the index file is loaded by default, and it's not part of the URL. So if the index.html is removed from the URL, the page would still work:
127.0.0.1:63688/#/
Loading student URL changes it to
127.0.0.1:63688/#/student
Which then loads StudentCntrl.
Related
I tried every solution on stackoverflow to make this error go but all to vain..
I am trying to use ngRoute to make SPA.
angular.js:14328 Error: [$controller:ctrlreg] The controller with the name 'loginCtrl' is not registered.
Here is my code
/* route file called controoler.js */
var app = angular.module('mainApp', ['ngRoute']).
config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login/views/loginView.html',
controller: 'loginCtrl'
})
.when('/reward', {
templateUrl: 'rewardManagement/views/reward.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
// loginCtrl in login/controllers/loginCtrl.js
var app = angular.module('mainApp', []);
app.controller('loginCtrl', ['$scope', '$location', function($scope, $http, $location) {
$scope.changeView = function(view) {
$location.path(view); // path not hash
};
}]);
<!-- -------index.html--------- -->
<!DOCTYPE html>
<html lang="en" class="body-full-height" ng-app="mainApp">
<head>
<script src="/controller.js"></script>
<script src="../login/controllers/loginCtrl.js"></script>
</head>
<body>
<div ng-controller="loginCtrl"></div>
<ng-view></ng-view>
</body>
</html>
<!-- -------loginView.html--------- -->
<script src="../login/controllers/loginCtrl.js"></script>
<div ng-controller="loginCtrl">
<button ng-click="changeView('/reward')">Please Bypass this for now</button>
</div>
Please suggest a solution, in my project I will have many links which when clicked should change the ng-view according to the route. And I don't think putting all the .js scripts in index.html is a good idea, shouldn't each partial contain its own .js which also contains the controller?
Here is the working Plunkr
Just did some little changes in your controller code:
app.controller('loginCtrl', ['$scope', '$location', function($scope, $location) {
$scope.changeView = function(view) {
$location.path(view); // path not hash
};
}]);
Also you don't need to add the script again in your loginView.html
The ng-view is not showing pages and routing doesn't seem to work but it is loading the angular-route.min.js in the browsers console/network.
The file structure is folders -> css, fonts, js, pages. there are 2 files in the root which are app.js and index.html and inside the pages folder are 2 more files which are the main.html and second.html which are supposed to be added to the ng-view parts but wont load.
When clicking on a link for the main.html content it comes back with http://127.0.0.1/main and completely ignores the /pages folder
**updated code, got the first page to load its content but the second one doesn't and there are no errors in the console so assumably I have the wrong href path?
Header Scripts
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="//code.angularjs.org/1.6.1/angular-route.min.js"></script>
<script src="app.js"></script>
HTML
<div class="row">
Main Content
Second Content
</div>
<div class="row">
<div class="col-md-12">
<div ng-view></div>
</div>
</div>
<hr>
</div>
JS
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateURL: 'pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateURL: 'pages/second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', function($scope) {
}]);
myApp.controller('secondController', ['$scope', '$log', function($scope, $log) {
}]);
Use templateUrl instead of templateURL.
In your html use #/main.
Don't use tow ng-views
JS code
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/second', {
templateUrl: 'second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', function($scope) {
$scope.name = "world"
}]);
myApp.controller('secondController', ['$scope', '$log', function($scope, $log) {
}]);
HTML code
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="//code.angularjs.org/1.4.0/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="mainController">
<p>Hello {{name}}!</p>
<div class="row">
Main Content
Second Content
</div>
<div class="row">
<div class="col-md-12">
<div ng-view></div>
</div>
</div>
<hr>
</body>
</html>
Here is working plunker
EDIT
Please note I have used angular version 1.4.0. If you want to use angular 1.6.1 they have changed default hash-prefix used for $location hash-bang URLs it is now ('!') instead of ('')
So you need to add this in your config phase.
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
now it will work with angular 1.6.1 as well
.when('/main', {
templateURL: 'pages/main.html',
controller: 'mainController'
})
or
use this url to access main page :
http://127.0.0.1/
It should work, as you have not set routing for main in config.
I have an Angular controller defined something like
mainCtrl.js
angular.module("mainCtrl", [])
.controller("mainController", function ($rootScope, $location, Auth) {
var vm = this;
vm.testStr = "If you see this, mainController is active on your page";
.
.
.
Here Auth is an angular service defined to handle authentication and it doesn't put the testStr variable behind authentication.
A view defined tries to bind the variable testStr as bellow
index.html
<html>
<head>
<base href="/">
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-animate.js"></script>
</head>
<body ng-app="userApp" ng-controller="mainController as main">
<main class="container">
<!-- ANGULAR VIEWS -->
<div><h3>{{main.testStr}}</h3></div>
<div ng-view></div>
</main>
</body>
</html>
But when the index is loaded the value of testString doesn't appear on the page. Instead {{main.testStr}} appears.
I am assuming it is not a must to use $scope and couldn't find what I am doing wrong.
Thanks in advance, for your help.
Edit
There are other files involved that I didn't mention here. Now I can see their relevance.
The app module,
app.js
angular.module("userApp", ["ngAnimate", "app.routes",
"authService", "mainCtrl",
"employeeCtrl", "employeeService"])
// application configuration to integrate token into requests
.config(function ($httpProvider) {
// attach our auth interceptor to the http requests
$httpProvider.interceptors.push("AuthInterceptor");
});
module for routing
app.route.js
angular.module("app.routes", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when("/", {
templateUrl: "app/views/pages/home.html"
})
// login page
.when("/login", {
templateUrl: "app/views/pages/login.html",
controller: "mainController",
controllerAs: "login"
})
// show all employees
.when("/employees", {
templateUrl: "app/views/pages/employees/all.html",
controller: "employeeController",
controllerAs: "employee"
})
// form to create a new user
// same view as edit page
.when("/employees/create", {
templateUrl: "app/views/pages/employees/single.html",
controller: "employeeCreateController",
controllerAs: "employee"
})
// page to edit a user
.when("/employees/:employee_id", {
templateUrl: "app/views/pages/employees/single.html",
controller: "employeeEditController",
controllerAs: "employee"
});
$locationProvider.html5Mode(true);
});
You have declared the Module name as mainCtrl
angular.module("mainCtrl", [])
but using ng-app as userApp
Change your module like this,
angular.module("userApp", [])
Your module name is wrong. It should be userApp instead of mainCtrl. See a working example below:
var myApp = angular.module("userApp", []);
myApp.controller("mainController", function($scope) {
var vm = this;
vm.testStr = "Hello";
});
<html>
<head>
<base href="/">
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-animate.js"></script>
</head>
<body ng-app="userApp" ng-controller="mainController as main">
<main class="container">
<!-- ANGULAR VIEWS -->
<div>
<h3>{{main.testStr}}</h3>
</div>
<div ng-view></div>
</main>
</body>
</html>
I have a standard angular page that is not associated with any ui.router functionality(index.html). From that page I click a link that triggers an angular call and than after some operation the flow needs to be redirected to a page inside a folder that is using angular-ui.route template.
I have created a plunker that represents this:
http://plnkr.co/edit/7UQTlMRQBMXGaRdHlPfs?p=preview (current plunker is working but there's a loop on first page trying to call default state created with $urlRouterProvider.otherwise('events');)
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.3.16" data-semver="1.3.16" src="https://code.angularjs.org/1.3.16/angular.js"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="LoginController as lgCtrl">
<h1>This page does not use ui.router</h1>
Login
</body>
</html>
The page with ui-view tag is inside a manage folder:
manage/home.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.angularjs.org/1.3.16/angular.js" data-semver="1.3.16" data-require="angular.js#1.3.16"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
<script type="text/javascript" src="../app.js"></script>
</head>
<body ng-controller="EventsController as evtCtlr">
<h1>Hello manage/home.html</h1>
<div ui-view></div>
</body>
</html>
The templateUrl page to be inserted is:
manage/events.html
<div ng-controller="EventsController as evtCtrl">
<h3>Events Page</h3>
<div>Some user email</div>
</div>
app.js
'use strict';
(function () {
var app = angular.module('app', ['ui.router']);
/**
* Configuration for ui-router module. Handles navigation based on app states.
*/
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('events');
$stateProvider
.state('events', {
url: '/events',
views:{
'#manage/home':{
templateUrl: 'manage/events.html'
}
}
});
});
app.controller('LoginController', ['$scope','$window', '$state',
function($scope, $window, $state){
$scope.goToEvents = function(){
console.log('trying to load events');
//this call doesn't work, 404 - It should?? -->> see reference
//https://github.com/angular-ui/ui-router/wiki/URL-Routing
$window.location.href = 'manage/home.html/events';
//don't work
//$state.transitionTo('events');
//also don't work
//$state.go('events');
};
}]);
app.controller('EventsController', [function(){
console.log('EventsController');
}]);
})();
I have created a plunker that represents this:
http://plnkr.co/edit/7UQTlMRQBMXGaRdHlPfs?p=preview
I have tried different ways of moving from the first non ui.router page but none worked so far.
What's the best way of doing this?
Firstly , do not inject $state as dependency in the LoginController as the view related to this controller isn't an UI route. Adding the $state dependency causes the loop that you are seeing in your example as UI-Router then considers this view a route. As no state matches this route , it tries to load the default state , whose template has a relative URL , which then looks it up inside wrong directory of Plunkr , which causes 404 error.
Secondly , the URL to redirect should via location.href should have a hash otherwise it will also give 404
The code for the LoginController
app.controller('LoginController', ['$scope', '$window',
function($scope, $window) {
$scope.goToEvents = function() {
//Do Something
$window.location.href = 'manage/home.html#/events';
};
}
]);
Check the working example at http://plnkr.co/edit/K2iBYu?p=preview
I configured a small angular app in tomcat its working fine, but when i tried to use route-Provider its not working.
I cannot route to my views.
I did not know why ?
Can any one give some small example for that.
My Code files
//this is controllers.js
var myapp = angular.module('sampleapp', []);
myapp.config('$routeProvider',function myRoute($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/admin.html',
controller: 'adminController'
})
when('/showdata', {
templateUrl: 'partials/data-view.html',
controller: 'dataController'
}).
otherwise({
redirectTo: '/'
});
});
adminController = function ($scope) {
$scope.message = "Welcome to Login Page";
}
dataController = function ($scope) {
$scope.message = "Welcome to Show Data Page";
}
myapp.controller(controllers)
my index.html
<html>
<base href="/advangularjs/" />
<head>
<link type="text/css" rel="stylesheet" href="css/default.css">
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script src="demoweb_angular/controllers.js"></script>
</head>
<body ng-app="sampleapp" style="background-color: #E0EEE0">
Login |
Show Data
<div ng-view align="center" style="border: 1px solid red;">
</div>
</body>
</html>
admin.html
<b>{{ message }}</b>
data-view.html
<b>{{ message }}</b>
Make sure you have added angular-route.js
in your index.html file.
Also Please go through the documentation of ui router for the basic setup
var myapp = angular.module('sampleapp', ['ngRoute']);
u need to add ngRoute dependancy also. Because your sampleapp is depend on ngRoute .
<div ng-view></div>
you need to add this also. the partial are loading to this div. put this inside the body.