Here, how I have configured the routing
var config = function (rp) {
rp.when(
'/docs',
{
templateUrl: 'Docs.htm'
}
);
};
config.$inject = ['$routeProvider'];
app.config(config);
then I added
Docs
to my htm page.
when the link is clicked, URL is changed to
my_pagename.htm#!#docs
and it does not load the template.
but when I manually type the URL in location as
my_pagename.htm#!/docs (replaced hash symbol with '/')
it loads fine.
Can you please tell me the error here?
what is the proper way of specifying the href attribute, in order to work with angular routing?
My angular version is 1.6.3
Why did you add # with href
try this
Docs
I don't know the consequences, but I changed the hrefs to
#!/<link>
Ex: #!/docs
#!/contacts
and now they work fine.
note that I didn't change route paths in js file.
Related
In this example:
const resolved = this.$router.resolve({
name: 'about'
})
console.log(resolved.route.path)
Is it possible to get route with origin included? Like, if the url is site.com/about, the code would give /about, so I'll need to append origin myself: window.location.origin + resolved.route.path.
I've been using this (tested with vue-router v4, browser only):
const route = router.resolve({ /* your route here */ });
const absoluteURL = new URL(route.href, window.location.origin).href;
Edit: Used location.origin instead of location.href since resolve().href already includes base.
No, not from the router.
Even the router's base property is relative to the app root:
The base URL of the app. For example, if the entire single page application is served under /app/, then base should use the value "/app/".
$route.fullPath also begins at the app root. The docs describe it as:
The full resolved URL including query and hash.
I am building an app with Phonegap and jQuerymobile. The app roughly works like this:
1) The app downloads a ZIP file from a public server and then unzips them to a local folder. I got the local folder path from fileSystem.root.toNativeURL() (in OS, it's something like this: file://var/mobile/Container/Data/Application/xxxx/Documents/)
2) App redirects to HTML that was unzipped in local folder (ex: file://var/mobile/Container/Data/Application/xxxx/Documents/index.html)
I am now facing issues b/c inside the index.html file, all the links are absolute path (ex: Link). This breaks all the links since (I assume) they are all now pointing to file://content/index2.html instead of file://var/mobile/Container/Data/Application/xxxx/Documents/content/index2.html.
My question is, how should I handle the links? I am thinking i should just rewrite all the links to force prepend the local folder URL in front of it. Is there a better way?
And if rewriting links is the way to go, how can I do this with jQuerymobile? I did this in jQuery which seems to work http://jsfiddle.net/jg4ouqc5/ but this code doesn't work in my app (jQueryMobile)
When you are loading index.html, you are getting file://some_path/..../index.html as your base URL. Any links which will be encountered now own-wards can be resolved in relation to the base URL.
You would know your scenario better. There could be multiple ways in which this can be fixed.
Have a contract with the CMS/Code generator. Links should always be generated either Relative to the base URL or Absolute. The links you are getting in the page are wrong - Link it ideally should be Link or fully qualified like https://www.google.com.
If you want to change the URL then you can use native code to change it after unzipping the content. It will be really straight forward.
If you want to change the URL in browser then you will have to persist the base url and then take care of couple of things:
a. absolute urls - In your case you can just check the window.location.protocol, if it starts with 'http' and then skip it.
b. sub-directories
Here is a small I have written:
Note: I have not tried this code and you might have to change it according to your need.
$(document).ready(function(){
var base_file_name = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
//In index.html (persist this value in native)
var baseUrl = window.location.href.replace(base_file_name, "");
$("a").each(function () {
this.href = baseUrl + this.pathname;
$(this).click(function (e) {
e.preventDefault();
alert(this.pathname);
window.location.href = this.href;
});
});
});
The example you linked should work, make sure you have the <base> set correctly and that you are using the correct string to replace.
Yeah, your going to have to normalize all URL's when your page loads. I can't test with phonegap right now, but your basePath will need to be one of the following:
The file path as you described in your answer (not likely)
window.location.origin (optionally including window.location.pathname)
CODE:
// mini dom ready - https://github.com/DesignByOnyx/mini-domready
(function(e,t,n){var r="attachEvent",i="addEventListener",s="DOMContentLoaded";if(!t[i])i=t[r]?(s="onreadystatechange")&&r:"";e[n]=function(r){/in/.test(t.readyState)?!i?setTimeout(function(){e[n](r)},9):t[i](s,r,false):r()}})
(window,document,"domReady");
domReady(function () {
var anchors = document.getElementsByTagName['a'],
basePath = /* get your base path here, without a trailing slash */;
Array.prototype.forEach.call(anchors, function( anchor ){
anchor.setAttribute('href', basePath + anchor.getAttribute('href'));
});
});
Remove the forward slash from the beginning of your links.
href="content/index2.html">
I'm trying to add an image to my AngularJS app with a url received from a random cat image site.
this is my controller.js:
'use strict';
/* Controllers */
var catPath = "http://thecatapi.com/api/images/get?format=src&results_per_page=1";
var Controllers = angular.module('museum1.controllers', []);
Controllers.controller('oneCatController', ['$scope', '$http',
function($scope, $http) {
$http.get(catPath).success(function(data) {
$scope.imgurl = data;
console.log($scope.imgurl);
});
}]);
and this is the partial that should show the image:
<div>
<img ng-src="{{imgurl}}">
</div>
the controller is called by the app.js, not shown here.
Using fireBug I get a message with the path i requested and "302 Found 770ms".
The same path works from the browser address line, and the angular code worked for me using this example.
A few things..
Usually I don't use double curly brackets for ng properties. You may consider removing them.
The case sensitivity of your controllers variable is different than that of the variable you access in ng-src. This may cause the ng-src value to not show up.
In the controller:
$scope.imgurl = data;
In the HTML:
<img ng-src="{{imageUrl}}">
Change your HTML to:
<img ng-src="{{imageurl}}">
Essentially, putting the 'U' into lowercase.
And finally, I'm not sure how the ng-src works off the top of my head. But, if it uses JavaScript to load the image--and your domain is not the same domain as the image you are loading, then you may be running into cross domain security issues. But, if ng-src does not use JavaScript to load the image somehow, then you should be fine.
On clicking hot kyes ctrl+t anywhere from my application it should redirect url to http://localhost:8080/myapp/account/create
i'm doing it by placing .js file in js folder and including that file in every page. thae content of .js file is
jQuery(document).bind('keypress', 'Ctrl+T',function (evt){
window.location.href =("http://localhost:8080/myapp/account/create");
return false
});
where myapp is Controller and create is the Action . so i don't want to hard code the entire url insted, whatever the url, only the controller and action should get replaced. so that in production environment i need not to change the url. this is grails application
As I understand you problem is to pass current context path into javascript, is it?
You can remember current context name in your view (in base layout, for example), put it into your <head> block:
<script type="text/javascript">
window.pageContext = '${request.contextPath}';
</script>
and then use it from other javascript like:
jQuery(document).bind('keypress', 'Ctrl+T',function (evt){
window.location.href = window.pageContext + "/account/create";
return false
});
Or, if you need to generate full path to your controller+action you have to use:
<g:createLink controller="account" action="create" />
see http://grails.org/doc/latest/ref/Tags/createLink.html for more information
Any smart way of doing a "root" based path referencing in JavaScript, just the way we have ~/ in ASP.NET?
Have your page generate a tag with something like:
<link rel="home" id="ApplicationRoot" href="http://www.example.com/appRoot/" />
Then, have a function in JavaScript that extracts the value such as:
function getHome(){
return document.getElementById("ApplicationRoot").href;
}
Use base tag:
<head>
<base href="http://www.example.com/myapp/" />
</head>
...
from now any link use on this page, no matter in javascript or html, will be relative to the base tag, which is "http://www.example.com/myapp/".
You could also use the asp.net feature VirtualPathUtility:
<script>
var basePath = '<%=VirtualPathUtility.ToAbsolutePath("~/")%>';
</script>
Notice: I don't encode the path to a JSON-string (escape quotes, control characters etc). I don't think this is a big deal (quotes for example aren't allowed unescaped in an URL), but one never knows...
I usually create a variable at the top of the js file and assign it the root path. Then I use that variable when referencing a file.
var rootPath = "/";
image.src = rootPath + "images/something.png";
~/ is the application root and not a literal root, it interpets ~/ to mean <YourAppVirtualDir>/
To do a literal root in JavaScript it's just /, i.e "/root.html". There's no way of getting an application level path like that in JavaScript.
You could hack it in the ASPX file and output it in a tag but I would consider the security implications of that.
Kamarey's answer can be improved to support a dynamic base path:
<head>
<base href="http://<%= Request.Url.Authority + Request.ApplicationPath%>/" />
</head>
This will ensure a correct root path regardless of deployment configuration.
To be fair, this doesn't answer the original question, but it elimiates most needs for getting the root path from javascript. Simply use relative URL's everywhere, without prefixing with slash.
Should you still need to access it from javascript, add an id attribute and use document.getElementFromId() as MiffTheFox suggested - but on the base-tag.
Another option that's a bit simpler and more universal would be to take the following:
<script src="/assets/js/bootstrap.min.js"><script>
and use Page.ResolveClientUrl like so:
<script src='<%=ResolveClientUrl("~/assets/js/bootstrap.min.js")%>'></script>
then regardless of what subdirectory the urls will always be rendered correctly.
The following function will calculate the root of the currently running application. I use it to locate the absolute location of resources, when called from somewhere deep within the application tree.
function AppRoot() {
//
// Returns the root of the currently running ASP application.
// in the form: "http://localhost/TRMS40/"
//
// origin: "http://localhost"
// pathname: "/TRMS40/Test/Test%20EMA.aspx"
//
// usage:
// window.open( AppRoot() + "CertPlan_Editor.aspx?ID=" + ID);
//
var z = window.location.pathname.split('/');
return window.location.origin + "/" + z[1] + "/";
}
In the PreRender of your .NET base page, add this:
protected override void
OnPreRender(EventArgs e) {
base.OnPreRender(e);
if (Page.Header != null)
{
//USED TO RESOLVE URL IN JAVASCRIPT
string baseUrl = String.Format("var baseUrl='{0}';\n",
HttpContext.Current.Request.ApplicationPath);
Page.Header.Controls.Add(new LiteralControl(String.Format(Consts.JS_TAG,
baseUrl)));
}
}
Then in your global JavaScript function, add the following:
function resolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url; }
Now you can use it like this:
document.getElementById('someimage').src = resolveUrl('~/images/protest.jpg');
May be a little much for some projects, but works great for full fledged applications.
Solution for ASP.NET MVC applications
This works when using IIS and also IIS Express in VS.
Put this snippet before all scripts load, in order to have the root url variable "approot".
at your service in the scripts:
<script>
var approot = "#Url.Content("~")";
</script>
--> other scripts go here or somewhere later in the page.
Then use it in your script or page script.
Example:
var sound_root_path = approot + "sound/";
var img_root_path = approot + "img/";
the approot variable will be something either:
"/YourWebsiteName/" <-- IIS
or just:
"/" <-- IIS Express
For ASP.net MVC Razor pages, Create a base tag like below in the <Head> tag
<base href="http://#Request.Url.Authority#Request.ApplicationPath" />
and in all your relative javascript URLs, make sure to start without a slash(/) otherwise it will refer from the root.
For ex. create all your urls like
"riskInfo": { url: "Content/images/RiskInfo.png", id: "RI" },
or
$http.POST("Account/GetModelList", this, request, this.bindModelList);
If you want to use it in HTML Still you can use ~, see this
href = #Url.Content("~/controllername/actionName")
See the check box click event in my MVC Application
#Html.CheckBoxFor(m=>Model.IsChecked,
new {#onclick=#Url.Content("~/controller/action("+ #Model.Id + ", 1)"),
#title="Select To Renew" })