How do I solve AngularJs -routing not working [duplicate] - javascript

This question already has answers here:
AngularJS All slashes in URL changed to %2F
(6 answers)
angularjs 1.6.0 (latest now) routes not working
(5 answers)
Closed 3 years ago.
I am writing some simple code to practice routing in angular. I have an index.html file which has links to access the respective templates and a div element to display the templates. The templates however do not show when the links are clicked and the url does not appear as expected.
url appears as:
http://localhost/angproj/#!#%2Fhome
instead of the expected http://localhost/angproj#/home
Here is the code:
Index.html
<!DOCTYPE html>
<html ng-app = "myModule">
<head>
<title>Home</title>
<link rel="stylesheet" href ="styles.css">
<script src="angular/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
<meta name="vieport" content="width=device-width initial scale=1">
</head>
<body>
<header><h2>Website Header</h2></header>
<div class="column">
<div class="links">
Home<br>
Our services<br>
Technologies<br>
</div>
</div>
<div class="content" ng-view></div>
<footer><h3>Website footer</h3></footer>
</body>
</html>
script file
var myApp = angular
.module("myModule",["ngRoute"])
.config(function($routeProvider){
$routeProvider
.when("/home",{
template:"About Us"
})
.when("/services",{
template:"Our Services"
})
.when("/technologies",{
template:"Our Technologies"
})});

The problem is the default hash-prefix used for $location hash-bang URLs is ('!') that's why there are additional unwanted characters in your URL.
If you actually want to have no hash-prefix and make your example work then you can remove default hash-prefix (the '!' character) by adding a configuration block to your application.
So your script file will be:
var myApp = angular
.module("myModule", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) { //inject $locationProvider service
$locationProvider.hashPrefix(''); // add configuration
$routeProvider
.when("/home", {
template: "About Us"
})
.when("/services", {
template: "Our Services"
})
.when("/technologies", {
template: "Our Technologies"
})
});
Full working example:
var myApp = angular
.module("myModule", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) { //inject $locationProvider service
$locationProvider.hashPrefix(''); // add configuration
$routeProvider
.when("/home", {
template: "About Us"
})
.when("/services", {
template: "Our Services"
})
.when("/technologies", {
template: "Our Technologies"
})
});
<!DOCTYPE html>
<html ng-app = "myModule">
<head>
<title>Home</title>
<link rel="stylesheet" href ="styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular-route.min.js"></script>
<meta name="vieport" content="width=device-width initial scale=1">
</head>
<body>
<header><h2>Website Header</h2></header>
<div class="column">
<div class="links">
Home<br>
Our services<br>
Technologies<br>
</div>
</div>
<div class="content" ng-view></div>
<footer><h3>Website footer</h3></footer>
</body>
</html>

Related

angular routing not working in Visual Studio 2015

It seems that by asking this question, I am just beating a dead horse, but I have been through all the posts that I could find and still could not find an answer. I (and even a colleague) have spent countless hours trying to solve what seems to be a relatively basic concept. So , can I please get some help with my angularjs routing
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="foodApp">
<head>
<meta charset="utf-8" />
<title>What Do I Eat</title>
<link href="/app/css/app.css" rel="stylesheet" />
<link href="/Content/bootstrap.min.css" rel="stylesheet" />
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/app/js/app.js"></script>
<script src="/app/js/controllers/ExistingRestaurantController.js"></script>
<script src="/app/js/controllers/NewExperienceController.js"></script>
<script src="/app/js/controllers/NewRestaurantController.js"></script>
<script src="/app/js/controllers/indexController.js"></script>
<script src="/app/js/services/RestaurantData.Service.js"></script>
</head>
<body>
<header class="container-fluid">
<h1>What Do I Eat</h1>
</header>
<div class="container-fluid">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>My Restaurants</li>
<li>Add Restaurant</li>
<li>Add Experience</li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
<footer class="container-fluid">
whatever i want
</footer>
</body>
</html>
app.js:
'use strict';
var foodApp = angular.module('foodApp', ['ngResource', 'ngRoute']);
foodApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/myRest',
{
templateUrl: '/templates/ExistingRestaurant.html',
controller: 'ExistingRestaurantController'
})
.when('/addExp',
{
templateUrl: '/templates/NewExperience.html',
controller: 'NewExperienceController'
})
.when('/addRest',
{
templateUrl: '/templates/NewRestaurant.html',
controller: 'NewRestaurantController'
});
}
]);
ExistingRetaurantController.js
'use strict';
foodApp.controller('ExistingRestaurantController',
function ExistingRestaurantController($scope) {
$scope.restaurant = {
name: 'Cheesecake Factory',
food: 'Cheesecake',
price: 6.95
}
}
);
ExistingRestaurant.html:
<div class="container-fluid">
<h1>Existing Page!</h1>
</div>
I think the problem is the project structure. Index.html appears to be nested within app. I thought the easiest fix was to move index.html to the root of the project. So with a folder structure of:
I was able to getting working as follows..
In Index.html, I changed the links to be #!/ (hash-bang):
<!DOCTYPE html>
<html lang="en" ng-app="foodApp">
<head>
<meta charset="utf-8" />
<title>What Do I Eat</title>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/app/js/app.js"></script>
<script src="/app/js/controllers/ExistingRestaurantController.js"></script>
<script src="/app/js/controllers/NewExperienceController.js"></script>
<script src="/app/js/controllers/NewRestaurantController.js"></script>
</head>
<body>
<ul>
<li>My Restaurants</li>
<li>Add Restaurant</li>
<li>Add Experience</li>
</ul>
<ng-view></ng-view>
</body>
</html>
Then in app.js I added the $locationProvider and set the hash-prefix to !. (I don't know why it's called hashPrefix because I always think it's a suffix, given that it comes after the hash, but I can live with it.)
'use strict';
var foodApp = angular.module('foodApp', ['ngResource', 'ngRoute']);
foodApp.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.hashPrefix("!");
$routeProvider
.when('/myRest',
{
templateUrl: '/app/templates/ExistingRestaurant.html',
controller: 'ExistingRestaurantController'
})
.when('/addExp',
{
templateUrl: '/app/templates/NewExperience.html',
controller: 'NewExperienceController'
})
.when('/addRest',
{
templateUrl: '/app/templates/NewRestaurant.html',
controller: 'NewRestaurantController'
});
}
]);
Your start path then becomes:
http://localhost:63317/index.html
and changes to the following when clicking the links:
http://localhost:63317/index.html#!/myRest
http://localhost:63317/index.html#!/addRest
http://localhost:63317/index.html#!/addExp
Well after 4 days of searching, I finally figured out my own answer. I was using angular version 1.6.1. The moment I rolled it back to 1.2.1, everything worked fine. I shall continue to research to figure out best routing practices.
Try rolling your angular version back until it works.

How create routes in AngularJS + JavaScript?

I'm creating a website and I'm using JavaScript + AngularJS, presently I create the routes for the application, but it always returns 404 not found on the server, I've tried several examples of the internet but none of them worked, here's an example of my code, remembering that The html pages are inside the WebContent:
<html ng-app="angularRoutingApp">
<head>
<title>Home</title>
<meta charset="utf-8">
</head>
<body>
<div>
index <br> home
</div>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.js"></script>
<script>
var angularRoutingApp = angular.module('angularRoutingApp', ['ngRoute']);
angularRoutingApp.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/index", {
template: "/index.html"
})
.otherwise({
redirectTo: '/home.html'
});
});
</script>
</body>
</html>
you forgot the ng-view directive.
also,
the href need to be with a hash prefix - or using the Link directive.
the redirectTo key need to provide a view [name/address] & not a
template
if you want to use template files & not inline code use the templateUrl key
you can see an example of your code here: http://codepen.io/AceDesigns/pen/ZLXLKa
<html ng-app="angularRoutingApp">
<head>
<title>Home</title>
<meta charset="utf-8">
</head>
<body>
<div>
index<br>
home
</div>
<div class="">
<ng-view></ng-view>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.js"></script>
<script>
var angularRoutingApp = angular.module('angularRoutingApp', ['ngRoute']);
angularRoutingApp.config(function($routeProvider){
$routeProvider
.when("/index", {template:"<div>INDEX VIEW</div>"})
.when("/home", {template:"<div>HOME VIEW</div>"})
.when("/tempFile", {templateUrl: "views/temp_file.html"})
.otherwise({redirectTo: '/home'});
});
</script>
</body>
</html>

AngularJs Controller in External file and using route

I have had a look through SO and nothing has helped.
This is my app.js
var app = angular.module("qMainModule", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/anonHome/anonHome.html',
controller: 'templates/anonHome/anonHomeController'
})
.when("/about", {
templateUrl: 'templates/anonHome/anonAbout.html',
controller: 'templates/anonHome/anonAboutController'
})
.when("/services", {
templateUrl: 'templates/anonHome/anonServices.html',
controller: '/templates/anonHome/anonServicesController'
})
.when("/contact", {
templateUrl: 'templates/anonHome/anonContact.html',
controller: '/templates/anonHome/anonContactController'
})
.when("/register", {
templateUrl: 'templates/anonHome/anonRegister.html',
controller: '/templates/anonHome/anonRegisterController'
})
.when("/login", {
templateUrl: 'templates/anonHome/anonLogin.html',
controller: '/templates/anonHome/anonLoginController'
})
$locationProvider.html5Mode(true);
})
app.controller("qMainController", function ($scope) {
$scope.Title = " Welcome to Qiao";
$scope.qNavigationTemplatePath = "/templates/topMenu/anonTopNavigation.html";
$scope.copyrightMessage = "Qiao ";
$scope.copyrightYear = new Date();
});
The routing works as expected and the partial templates are being shown but the partial templates controllers are not being recognised as a function.
The Layout Template looks like this
<!DOCTYPE html>
<html ng-app="qMainModule">
<head ng-controller="qMainController">
<base href="/" />
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Qiao :: {{Title}}</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="../css/modern-business.css" rel="stylesheet" />
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="/scripts/angular.js"></script>
<script src="../scripts/angular-route.js"></script>
<script src="/app/app.js"></script>
<script src="templates/anonHome/anonHomeController.js"></script>
<!-- <link href="../styles/qiao.css" rel="stylesheet" /> -->
</head>
<body ng-controller="qMainController">
<div ng-include="qNavigationTemplatePath">
</div>
<!-- Page Content -->
<div class="container">
<ng-view></ng-view>
</div>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12" ng-controller="qMainController">
Copyright © {{copyrightMessage}} {{copyrightYear | date:'yyyy'}}
</div>
</div>
</footer>
<div >
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Script to Activate the Carousel -->
<script>
$('.carousel').carousel({
interval: 5000 //changes the speed
})
</script>
</div>
</body>
</html>
The partial template looks like this:
<script src="anonHomeController.js"></script>
<div ng-controller="anonHomeController">
<h1>{{Title}}</h1>
</div>
and its controller is this
function anonHomeController($scope) {
$scope.Title = " Welcome to Qiao";
$scope.qNavigationTemplatePath = "/templates/topMenu/anonTopNavigation.html";
$scope.copyrightMessage = "Qiao ";
$scope.copyrightYear = new Date();
};
The Question: How do I get Angular to recognise and use the partial template's controller?
While defining a controller, don't use any directory paths.
From the docs - https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
controller – {(string|Function)=} – Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
Note that the registered controller never has the entire path, it is the function definition itself or the function's name (a string). You may need module names, if you have exported like that, but that's different from a directory path.
All you need is just use <script> tags in index.html, which will include all your functions. Now if your functions are just plain javascript, and you don't intend using angular.module('app').controller there, use it in the app.js, Just angular.module('app').controller('anonHomeController', anonHomeController); Note that your definition can still remain in the Javascript file /some/path/totemplate/anonHomeController.js. I suggest you try that and see if it works.
app.js
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/main/main.html',
controller: 'MainCtrl'
})
index.html
<script src="controllers.js"></script>
controllers.js
function MainCtrl ($scope) {
$scope.name = 'World';
}
A working plnkr here
You have created your controller for each view as a regular JS function, which is incorrect. It should be like
app.controller("anonHomeController", function ($scope) {
$scope.Title = " Welcome to Qiao";
// rest of the controller code
});
and the file should be anonHomeController.js at the path you have defined in the config. you also do not need to include the scipt tag in the header of the view. Check for some example here
You don't need to add complete path in your app.js for defining controllers.
If you're controllers are defined in the same file, then this should do the job:
$routeProvider
.when("/", {
templateUrl: 'templates/anonHome/anonHome.html',
controller: 'xyzController'
});
app.controller("xyzController", function ($scope) {
// controller function here
});
If you want your controllers to be in an external file, you'll have to do the following:
1. Define the controllers module:
angular.module('app.controllers', [])
.controller("homeController", function(){....})
Name this file as controllers.js
2. Now your main app.js should include this:
angular.module('app', [
'app.controllers',
])
Include controllers.js in your main html file

"win-list-view" element break page in Universal windows 8.1 project with WinJS and Angular

I try simple Universal windows 8.1 project.
My default.html page:
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<meta charset="utf-8" />
<!-- WinJS references -->
<script src="scripts/services/winstore-jscompat.js"></script>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/winjs/js/base.min.js"></script>
<script src="node_modules/winjs/js/ui.min.js"></script>
<!-- angular -->
<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/angular-route/angular-route.min.js"></script>
<script src="node_modules/angular-winjs/js/angular-winjs.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/EventsController.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
Project has one simple view and simple controller. When I use "win-list-view" in my view, (even empty win-list-view without bounding) I got error which i do not understand.
HTML1300: Navigation occurred.
default.html
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
default.html
Error: [$compile:noslot] http://errors.angularjs.org/1.5.3/$compile/noslot? p0=true&p1=%3Cdiv%20class%3D%22ng-isolate-scope%22%20item-data- source%3D%22manufacturers%22%20ng-transclude%3D%22true%22%3E
...
My page is open, but data on screen are in json format. Whole data binding array is shown on screen.
View:
<div>
<win-list-view item-data-source="manufacturers">
<win-item-template>
<div>
<h4>{{item.data.title}}</h4>
<h6>{{item.data.text}}</h6>
</div>
</win-item-template>
<win-list-layout></win-list-layout>
</win-list-view>
</div>
Controller:
(function () {
angular.module("mainApp")
.controller("EventsController", function ($scope) {
$scope.manufacturers = [
{ title: "marvelous mint", text: "gelato" },
{ title: "succulent strawberry", text: "sorbet" },
];
})
}());
My app:
(function() {
angular.module("mainApp", ["ngRoute", "winjs"]);
angular.module("mainApp")
.config(function ($routeProvider) {
$routeProvider
.when("/events", {
templateUrl: "views/events.html",
controller: "EventsController"
})
.otherwise({ redirectTo: "/events" });
});
}());
Why "win-list-view" tag on view caused that error?
Work on windows 8 with VS2015, maybe it has influence.

AngularJS v1.3.13 ng-view not triggering controller to render template

Having an issue using the ng-view to render a template from my controller.
The index.html file is initially served to the client and looks like.
<!doctype html>
<html lang="en" ng-app="hlmApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title></title>
<link rel="stylesheet" href="#Model.Root.Resource/bower_components\\/bootstrap/dist/css/bootstrap.css">
#RenderSection("BootScript")
<!-- app.js will load the angular module -->
<script src="#Model.Root.Resource/bower_components/angular/angular.js"></script>
<script src="#Model.Root.Resource/bower_components/angular-route/angular-route.js"></script>
<script src="#Model.Root.Resource/app/app.js"></script>
<script src="#Model.Root.Resource/app/controllers/controllers.js"></script>
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>A link here</li>
</ul>
</div>
</div>
<div ng-view></div>
#*<div ng-controller="tempController">{{Heading}}</div>*#
</div>
#RenderBody()
</body>
</html>
the server pushes down my app.js and controllers.js file along with the deps.
/// ap.js ///
var hlmApp = angular.module('hlmApp', ['ngRoute', 'MyTempControllers']);
hlmApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/Holdings', {
templateUrl: 'templates/temp.html',
controller: 'controllers/tempController'
});
}]);
the controller is pretty simple and is as follows
var MyTempControllers = angular.module('MyTempControllers', []);
MyTempControllers.controller('tempController', ['$scope', function () {
console.log("stuff happening");
$scope.Heading = "Hello World";
}]);
then the html template is as follows
<div>
<h3>{{Heading}}</h3>
</div>
When I use the ng-view nothing ever renders. the controller is never triggered in the debugger. If I specifically call out the controller via the ng-controller then everything shows up. can someone point out my error here?
You need these 3 changes:
1) add $scope as a parameter in your controller function
MyTempControllers.controller('tempController', ['$scope', function ($scope) {
...
}]);
2.
Change
controller: 'controllers/tempController'
to
controller: 'tempController'
FYI, the naming convention for a controller is to begin with a capital letter for Controller.
3. In addition, you should add a
.otherwise({
template: templates/temp.html,
controller: 'tempController'
});
so that when no route matches, it goes to default-page-name.html. This is what's happening in your case, when you first load the page, no route matches. If you want to see temp.html, you have to 1) either click on a link that goes to #/Holdings, or 2) use '/Holdings' as the "otherwise" route, as indicated above.
Try this:
hlmApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/Holdings', {
templateUrl: 'templates/temp.html',
controller: 'tempController' // just the name
});
}]);
and also $scope is missing in parameters:
MyTempControllers.controller('tempController', ['$scope', function ($scope) {
console.log("stuff happening");
$scope.Heading = "Hello World";
}]);

Categories