Angular Partials: templateUrl Routing Local .HTML File - javascript

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.

Related

Angular routing behaving strange/differently with different browsers

I just finished coding a new web project using AngularJS and Bootstrap. The development took place using Brackets, an editing tool that launches Chrome for testing while functioning as the web server.
So far, everything works as required both when Brackets is used as the server as well as when the whole project is deployed within a Tomcat installation, and this as long as the browser being used is Chrome and the machine is a Windows 10 computer.
Now, I started testing the project using different browsers and devices (e.g tablets, mobiles, etc.) and, oops! I am getting crashes all the time.
It would appear that the first (and perhaps central) issue is coming from the way I implemented and use Angular's routing services (or, at least, this is what is suggested by several posts I found). Two things are happening (depending on the browser and the action triggered) pointing in that direction:
I received many times the error infdig, meaning that there is an infinite reload loop somewhere,
When the user successfully logs into the the system, an object containing the user's details is stored as a $rootScope object, and when a $window.location.href command is used to move to other page, all the user information previously stored disapears (strangely, this s not happening with Chrome, but it is with IE and Edge!).
Unfortunately, I was unable to fully understand what is the proper way of using the routing services.
The structure of the project is:
[MyApp] -- This is the folder containing the whole project under TOMCAT's "webapps" folder
index.html
index.js -- Contails the controller related ot the index.html page
[pages] -- Sub-folder hosting all the pages of the project except for the `index.html`
page1.html
page2.html
:
:
[js] -- Sub-folder hosting the controllers of each and every sub-page
page1.js -- Sub-page controller
page2.js -- Sub-page controller
:
:
Transition to the sub-pages (e.g. page1.html, etc.) takes place using the command $window.location.href = "#page1.html";, and the routing service is defined:
$routeProvider
:
:
.when('page1.html', {
templateUrl: '#/pages/page1.html',
controller: 'Page1Controller'
}
.when('page2.html', {
templateUrl: '#/pages/page2.html',
controller: 'Page2Controller'
}
:
:
Based on some posts related to how to define routing, I also tried:
.when('page1.html', {
templateUrl: 'pages/page1.html',
controller: 'Page1Controller'
}
and
.when('page1.html', {
templateUrl: '/pages/page1.html',
controller: 'Page1Controller'
}
getting errors in both cases (e.g. page not found).
Additionally, it is not clear to me what is the impact of including the statement $locationProvider.html5Mode(true); (when including this, I got an injection error).
How can I properly use this Angular routing service, and how can I set HTML5 mode?
Routing params: the way I've done it and it works for me and its simple is using the same route function I showed before:
Then if you look at 'searchresult/:searchCriteria' :search criteria is already a parameter that I am putting in a JavaScript variable called sys (i.e at the beginning of my JavaScript I declare variable var sys = null;).
Then on the SearchResult Controller I put the value of sys inside a $scope variable let's say $scope.sys = sys;. This gives you the variable both in the scope and in JavaScript if you want to check the values in developer tools console and/or play with them.
To call the pafe http://url/#searchresult/myvalue
Just like before call $location.path("/searchresult/myvalue")
like this you can create a path with many arguments (i.e "/searchresult/myvalue1/myvalue2/myvalue3") and they all will be stored in the variable sys
PS: if you want to change your whole url use window.location.replace('new url') without any $. The difference between this routing and the Angular is that this will refresh the page while angular will only refresh your ng-view
Regarding the page not found issue make sure that templateUrl: 'pages/page2.html' has the same path as in the actual folders
- capital letters
- the s in "pages" is also present in the pages folder
Also make sure that the permission are ok such that your application is not getting denied access to the file. I don't know what OS you are using but make sure your application can access it
Regarding the loop error, to help I would need to see a bit more code, but if you open the application in Chrome and see the error in the developer tools it may give you a hint as of where your application is crashing. The other approach is to start commenting part of the application until you don't get the error to find the problematic line then analyze.
This is an example of a controller I use without problems:

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

AngularJS HTML sub routes not showing when url typed in

I have AngularJS setup to use HTML5 routes and it works great on urls like website.com/foo but when I create routes for sub pages, eg: website.com/foo/bar it only shows the correct page when clicking a link to it on my site. If I type the url into my browser and attempt to directly access it I get a blank page section where the ng-view content should be loading.
app.when('/promotion/events', {
templateUrl: '/assets/tpl/promotion/events/home.html',
controller: PromotionEventsCtrl
});
It appears to be a bug in Angular 1.1.5 that is effecting URL parsing in HTML5 routes. Rolling back to 1.1.4 fixes the problem.
More information here: https://github.com/angular/angular.js/issues/2833

Angular Routing & the ng-view

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

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