Angular Routing & the ng-view - javascript

How does angular know to make a request for the template view that contains 'ng-view' element?
If I navigate in my application say directly to
http://localhost/Categories/List/accessories
. A request is still made to '/ or the index template' as this contains the 'ng-view' element needed to render all the views.
When I navigate from the index to /Categories/List/accessories no request is made for the index again.
Below is my basic routing which has been copied in part from the Angular MVC "CookBook" example on GitHub
angular.module('myApp', ['myApp.ctrl.list'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/Home/Splash',
});
$routeProvider.when('/Categories/List/:slug', {
templateUrl: '/Categories/List',
controller: 'listCtrl',
});
$routeProvider.otherwise({
redirectTo: '/'
});
}]);

With your routing configuration, I believe your example url is missing a pound sign (#), so it should look like:
http://localhost/#/Categories/List/accessories
The part after the # sign is the path intended to be resolved by AngularJS (ie. the routing configuration you have defined)
When you enter the above URL into the address bar of the browser, the browser automatically looks for index.html on localhost. Most browsers, if not all, are set to look for index.html when only the domain name is present in the URL.
What about the part after the # sign? You might ask. The path after the # sign does not get sent to the server, by definition, and thus the browser could care less of what that part is consisted of.
In the second scenario you mentioned, AngularJS does not request for index.html because it's been cached the first time it was loaded and that cached copy is used.

Is your locationProvider configured for HTML5?
$locationProvider.html5Mode(true);
See Using HTML5 pushstate on angular.js

Related

Removing the hash from the url in AngularJS 1.x [duplicate]

This question already has an answer here:
AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors [duplicate]
(1 answer)
Closed 4 years ago.
I'm building a web app with Angular 1.x(not using ionic, building a website). I would like to remove the '#' from the URLs. I did implement html5mode true and put a base tag in the head tag in index.html. It works fine until I refresh the pages. When it is in html5mode it thinks that the URL is a request to the server. I'm developing in the local environment with gruntjs using the grunt-contrib-connect plugin and hosting my website in GoDaddy hosting in Linux Hosting Server. I would like to configure the html5mode(removing the hash from the URLs) in both environments(development and production). Note: I'm using ui.router with states if it matters in this problem.
By default, AngularJS will route URLs with a hash(#).
For example:
http://example.com/
http://example.com/#/about
http://example.com/#/contact
To remove the hashtag from the URL, you need to do two things
Configuring $locationProvider
Setting our base for relative links
$location Service
In AngularJS, the $location service parses the URL in the address bar and makes changes to application and vice versa.
$locationProvider and html5Mode
We will use the $locationProvider module and set html5Mode to true.
We will do this when defining Angular application and configuring routes.
angular.module('stackoverflow', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
controller : homeController
})
.when('/about', {
templateUrl : 'partials/about.html',
controller : aboutController
})
.when('/contact', {
templateUrl : 'partials/contact.html',
controller : partialController
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
Setting Relative Links
To link around application using relative links, we will need to set a <base> in the <head> of your document.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="/">
</head>
There are many other ways to configure this and the HTML5 mode set to true should automatically resolve relative links.

Concept of $location

I don't understand this. In my local I am trying to develop a website. In that website links are working in app but when I try to F5 or copy that link and paste it to browser I am getting 404 Page Not Found error. I google it and found that this related to parsing URLs but cant figure out how to do this. Here is my code:
Javascript
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('baba', {
url: "/",
templateUrl: "baba.html"
})
.state('icerik', {
url: "/icerik/:ad",
templateUrl: "icerik.html",
controller: "mmgCtrl",
})
.state('oku', {
url: "/oku/:serix/:klasor",
templateUrl: "oku.html",
controller: "nbgCtrl"
})
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
.controller('indexCtrl', function($scope, $location) {
$scope.yonlen = $location.path();
})
I have two routes. /icerik and /oku. So I think I should do if statement to which url going to which scopes.
index.html
<div ng-repeat="manga in mangas">
<a ng-href="{{yonlen}}></a>
</div>
Under the hood, this uses pushState.
When you change the state of the page with JavaScript, you should change the URL to one which would cause the server to generate the page in that state.
That would mean that if the JavaScript failed for any reason, the content would still load correctly and that if someone followed a deep link, they would directly (and thus quickly) load the content they were actually concerned with.
For example:
The visitor arrives on the homepage
The server delivers the homepage (plus all the angular code)
They click the "blog" link
You load blog content and put it on the page (with JS)
You change the URL to /blog/ (still with JS) without loading a fresh page from the server
But then:
The visitor arrives on the blog
The server delivers the blog page (plus all the angular code)
You're doing the change the URL but but haven't done the put the right content at that URL bit. That requires server side work.

Throwing cannot get error after enabling html5Mode in AngularJS

I am using UI-Router for routes/states in my app and URLs were having "#" so to remove this , I used $locationProvider like -
function configState($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
Added ngRoute in module dependency and added <base href="/" > in my index.html.
Problem -
If I am using it as a normal app like in same tab and navigates to other state, it works BUT whenever I pasted the URL in another tab and hit enter its throwing Cannot GET /app_views/contacts URL is like - http://localhost:9000/app_views/contacts
Though with hash in URL it works in both way manner.
You are likely getting this error because your server is not configured correctly. In other words when you manually enter /app_views/contacts it will make a request to the server for that page. For this to work properly you need configure your server to route all traffic to your index.html page in order for Angular to properly take over and display the correct view.
Here is a related post Reloading the page gives wrong GET request with AngularJS HTML5 mode

Angular Partials: templateUrl Routing Local .HTML File

I've had this problem for over 2 days and I've spent around 10 hours researching, but NOTHING has worked so far. I'm keeping my stress levels in check, but this is downright infuriating!
This jsfiddle has everything aside from the "page1.html" file that I'm trying to load
http://jsfiddle.net/tAmr3/
I want to load a sibling (same directory), page1.html file as such:
var playground = angular.module("playground",['ngRoute'])
.config(function($routeProvider){
$routeProvider.when('/Page1', {
templateUrl: 'page1.html', // **THIS LINE DOES NOT WORK**
controller:'page1Ctrl'
}).otherwise({redirectTo:'/'})
});
The problem is that "templateUrl" refuses to work!!!
The $routeProvider knows when I'm trying to access Page1 because page1Ctrl is console.logging successfully
The problem here was serving the angular app over file:// and having Angular trigger a cross-origin request when it tried to fetch the template over http://.
The easiest solution to that is to use a webserver rather than accessing the file-system directly.

Express loads controller infinit times and browser windows crashes when I use subpath

I'm currently working with angularJS and I try to build a homepage. My routeconfig looks like this:
var app = angular.module('mml-annie', ['mmlServices']);
app.config(['$locationProvider', function($location) {
$location.html5Mode(true); //now there won't be a hashbang within URLs for browers that support HTML5 history
}]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/team', {
templateUrl: 'partials/team',
controller: TeamCtrl
}).
otherwise({
redirectTo: '/home'
});
}]);
For testing purposes my controler looks like this:
function TeamCtrl($scope, Team) {
console.log("TEST");
}
Everything I working fine except when my path get additions / fields. When I change "/team" to "/team/team/test" my app calls the controller until the app crashes. Not using html5 mode fixes the problem. But I would rather use the nice HTML5 mode without the hashbang.
The app runs on node.js with express which serves the angular app for all requests except API calls.
Do you have any idea what is happening? I have no clue...
Of course I can provide further information if needed.
the solution is as follows:
My partials didn't have the relative path prefix "/". So whenever i tried to advance in a path the server looked for a partials that wasn't there, for example: /team/partials/team
Node then sent the basic layout which had itself the ng-view div again and started all over.
Why do I always fiddle around for like 2 hours - then decide to write a question and 2 minutes later I find the answer....

Categories