How to update base relative URL in angularapp? - javascript

So I have an existing angular app which routes/imports (eg: href and src) from the root path only (ie: /). So the app loads up at http://localhost:8080/ and and the base url is /. I want to change it to be http://localhost:8080/myapp/ so all links will then prefixed with /myapp.
I tried updating this code here from (it's in a Java jsp called app.jps):
<head>
<base href="/" />
to
<head>
<base href="/myapp" />
But this did nothing, I still get errors like this (and others like it): angular.js:11630 GET http://localhost:8080/angularapp/home/home.html?version=4 404 ()
There are many other errors like this, and the page is just blank (white) so far. Do I have to go and piecemeal edit all these urls to include /myapp in front of it? OR is there a better way?
More info:
Template Urls look like this (in app.module.js):
$stateProvider
.state('home', {
url: '/',
templateUrl: '/angularapp/home/home.html?version=' + window.version,
controller: 'HomeCtrl',
controllerAs: 'vm'
})

It seems like you are missing the end slash.
<head>
<base href="/myapp/" />
Please update href to "/myapp/", that should work.

If you change your templateUrl to:
templateUrl: './angularapp/home/home.html?version=' + window.version,
it should take it as a relative path.
Try that and see what it gives you (assuming your base url already comes off http://localhost:8080/myapp/).

Related

Not load a JS file for a specific path

I have a website by mean-stack.
Normally, all my external references are listed in index.html
I realize that one external JS library (e.g., https://cdnjs.cloudflare.com/troublelibrary.js) I am using has some conflit with a part of my website. So a workaround I am looking for is to NOT load it for a specific path https://www.myexample.com/specific.
Does anyone know how to achieve this in the routing?
Edit 1: (see the full question here)
Actually, the library that has conflit is history.js. My initial code which loads it all the time is as follows. As a result https://localhost:3000/home in a browser is always https://localhost:3000/home (i.e., will not add # because of history.js)
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js"></script>
Then, if I try the following code, as Ben suggests:
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script>
var newScript = document.createElement('script');
newScript.src = 'https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js';
document.head.appendChild(newScript);
console.log(window.location.href)
</script>
I realize that for the first time of loading https://localhost:3000/home will not change. But, if I refresh the browser, it can change to https://localhost:3000/#/home.
So appending the script is not exactly the same as a direct reference, does anyone know why?
I see your problem in a different perspective. You mentioned that you use the history.js to avoid # on the URL. But you do not need history.js to do that. I think you understood your problem in the wrong way. There is an inbuilt Angular functionality to get rid off # paths. Because # is used to keep track of the relative path on any route. If we want we can override that default functionality.
But if you use this approach the server should responsible to redirect the user to index or home page on any application route since Angular handle all the routing in the application.
First you should add
<base href="/" />
in your HTML file.
Then you should enable HTML5 Mode inside Angular application as follows.
$locationProvider.html5Mode(true);
By adding these two attributes you can get rid off the # path and this is the recommended way.
Following is a complete example.
var app = angular.module("app", ["ngRoute"]);
app.controller("MainController", function($scope){
});
//Add route handler
app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
template: '<h1>Home</h1>',
reloadOnSearch: true
})
.when('/about', {
template: '<h1>About</h1>',
reloadOnSearch: true
}).otherwise({
redirectTo: '/'
});
// This will remove hash bang from the routes
$locationProvider.html5Mode(true);
}]);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.js"></script>
<base href="/" />
</head>
<body>
<div>
Home
About
</div>
<div ng-app="app" ng-controller="MainController">
<ng-view></ng-view>
</div>
</body>
</html>
As you can see on the above example when you click on the about link the server responds with not found on /about. This means the # bang is removed.
This is one way to do it:
if(window.location.href !== 'https://url.com/path/to/trouble/page'){
var newScript = document.createElement('script');
newScript.src = 'https://url.com/path/to/script';
document.head.appendChild(newScript);
}
Add this to the <head> of the document. It will not load the trouble script on the page you specify in the if statement. Make sure not to load the trouble script anywhere else on the page as well.
you can do lazy loading of script in angular
<script type="text/javascript" ng-src="{{exUrl1}}"></script>
and somewhere in your code (based on whatever logic you want)
$rootScope.exUrl1 = $sce.trustAsResourceUrl(confserver.example.url);

Angular 1 Base href and routing/views/controllers

I am looking to add a base href to my webapp. Currently everything runs correctly when running:
localhost:3000/#/login
But i need to add base href or "charge" -> localhost:3000/charge/#/login
Current index.html
<head>
<base href="charge/" />
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" ....
</head>
Anuglar Route File
function routerConfig($routeProvider, $locationProvider) {
$routeProvider
.when('/map', {
templateUrl: 'app/views/main/main.html',
controller: 'MainController',
controllerAs: 'mainCtrl'
})
.when('/login', {
templateUrl: 'app/views/login/login.html',
controller: 'LoginController',
controllerAs: 'loginCtrl'
})
.when('/list', {
templateUrl: 'app/views/list/list.html',
controller: 'ListController',
controllerAs: 'listCtrl'
})
.when('/reporting', {
templateUrl: 'app/views/reporting/reporting.html',
controller: 'ReportingController',
controllerAs: 'reportingCtrl'
})
.otherwise({
redirectTo: '/map'
});
// $locationProvider.html5Mode(true);
}
Whenever i run my app with the basehref and navigate to localhost:3000/charge/#/login, basically every view, controller, bower component, and the module cannot be found. I have tried editing the router, changing the name of the main app folder but cannot get this to work. I know i am missing something small so any help is greatly appreciated!
My issue seems very similar to Base Href and Angular Routing and Views but i honestly just cannot figure this out.
If you're using Chrome and you look in the developer console, look at what the URL for the resources it can't find:
http://localhost:8080/charge/app.js
It is looking at the root of the project, and then for a folder called charge, and then for the resource.
The HTML element specifies the base URL to use for all relative
URLs contained within a document. There can be only one element
in a document. - MDN
Can you tell us what your directory structure looks like here? If your project files are directly in root, try making a subfolder named "charge" and put all of your files in it.
Example: root > charge > project files
Helpful link: AngularJS: Changing App Path, and the Element
Try prepending a "/" before all of your source URLs. This will begin each path at the root directory of your project rather than at your base href.
e.g. templateUrl: '/app/views/main/main.html'

Angular best practice for writing links (path, href) with html5 mode

I am looking for best practices to write links and paths in Angular 1.5.
Given the following configuration:
angular.module('my-app', ['ngRoute'])
.config(function ($locationProvider) {
$locationProvider.html5Mode({enabled: true});
});
This does not work when I have a base ref in the html document:
<html>
<head>
<base href="/my-app/"/>
...
</head>
<body>
<a ng-href="/my-section">My section</a>
</body>
</html>
Clicking the link put me at the absolute url /my-section, which does not exists. The same goes for the location service:
$location.path('/my-section') // Change my url at /my-section, not /my-app/my-section
It is easily fixed by replacing all my links with relative ones which has the effect or redirecting me to /my-app/my-section accordingly:
<a ng-href="my-section">My section</a>
$location.path('my-section')
However, according to the documentation of $location service:
Path should always begin with forward slash (/), this method will add
the forward slash if it is missing. https://docs.angularjs.org/api/ng/service/$location
This is basically telling me that the recommendations are to start all links with forward slash. How this is possible in my case ?
I think you should give only '/' as base href, if your app index looks like 'http://example.com/'.
If your index url looks like 'http://example.com/my-app/' then base href value would be '/my-section'.
Actually, it depends on url of the index page. So, please go by this way :)
<html>
<head>
<base href="/"></base>
...
</head>
<body>
<a ng-href="my-app/my-section">My section</a>
</body>
</html>
Set base URL as forward slash

redirect with angularJs to other project

My URL is like : http://localhost:3000/family/#/savings/subscribe/123456
in this page, I want to click on a button to redirect me into other page of another project made with backbone JS
I tried to add the needed URI with href- and ng-href http://localhost:3000/admin#exemption : but it always redirect me to http://localhost:3000/family/#/admin#exemption
angular.module('app', ['ng', 'ngRoute', 'ui.bootstrap', 'angularMoment', 'chart.js'])
.config(fac['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/index', {
templateUrl: '/family/index',
controller: 'IndexCtrl'
})
.when('/family/exemption', {
templateUrl: 'exemption-search-view'
})
when i gave the template of the needed page, I obtain the html view but the URI : http://localhost:3000/family/#/admin#exemption
I'm not sure to understand the question, but if you wanto to avoid angular routing interception, you should add in your anchor target="_self".
<a ng-href="{{vm.logoutUrl}}" target="_self">Bye!</a>
Instead of redirecting with the href (or any variant) try using a function in a controller which redirects you to the new url. Try something like this:
// in your controller
angular.module('app', ['ngRoute'])
.controller('redirectCtrl', function($window, $location){
var vm = this;
vm.wizard = {
anotherurl: "http://example.com",
redirect: fnRedirect
}
return vm.wizard;
function fnRedirect(link){
//this way is useful if you try to redirect to an external URL
$window.location = link;
//this way is useful if you try to redirect to another route inside the same angular project
$location.path(link);
}
});
...and in your html...
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body data-ng-controller="redirectCtrl as rc">
<input type="text" data-ng-model="rc.anotherurl" />
Redirect me
</body>
</html>
If your other project is not part of your angular app, you should redirect to another URL.
Just use .
ng-href is here to append the URL you're passing after the hash in the URL.
The problem in Angular, it redirects you to the same base in his URL, so if you want to change the base (which is /family/#/ in my case), it is like you are going to an external URL from the project so I had just added in my controller :
$window.location.href ='http://localhost:3000/admin#exemption' ;
I don't need any update in my '$routeProvider'

AngularJS routing to static file

I have a simple angularjs app, with ngRoute module for routing in html5Mode.
How can I have a link to some static file on my page, and not to have it intercepted by angular routing module?
Here's the example:
HTML:
<head>
<base href='/'></base>
</head>
<body ng-app="crudApp">
Home
User
users.html
<div ng-view></div>
JS routing:
$routeProvider
.when('/', {
templateUrl: 'app/components/home/homeView.html',
controller: 'HomeController'
})
.when('/user', {
templateUrl: 'app/components/user/userView.html',
controller: 'UserController'
})
.otherwise({
redirectTo: '/'
});
When I click on User link I get routed to localhost:8080/user, and my controller and template work fine. When I click on users.html link I get routed to home, but I want to invoke a static home.html page.
From the AngularJS docs, you have 3 options:
Html link rewriting
(...)
In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.
Links that contain target element
Example: link
Absolute links that go to a different domain
Example: link
Links starting with '/' that lead to a different base path
Example: link
What you might be looking for is the first example:
users.html

Categories

Resources