$state.go changing url having /#q=hello to /#/q=hello - javascript

I am working on a chrome extension which injects some content script in google.com.au. That content script then loads up an angular ui router based app having a small interface. I am using $state without url. So only templateUrl and controller. The problem is when I use $state.go('home') to go to home page of my small app, $state.go in internally changes the location or url from for e.g.
(1) :- https://www.google.com.au/#q=hello
to
(2) :- https://www.google.com.au/#/q=hello
(there is an extra / after q)
the second url is invalid one which redirect me back to google.com.au.
Also, its worth mentioning that - the same app worked fine when I injected it in a linked search results page whose url didn't have any # in it.
Also, I have tried variations like $state.go and $state.transitionTo with third parameter of {location:false ....}. but it stills changes the urls like above.
I am stuck and not able to go ahead with logic ahead.
here is screencast of the problem.
http://screencast.com/t/ZrBtlkU3z
Any help will be highly appreciated.
Thanks in advance.
Update
Here is an example chrome extension containing the mentioned problem.
https://Vikasg7#bitbucket.org/Vikasg7/example-app.git
Please load this as unpacked extension and try to go to
https://www.google.com.au/#q=hello
before and after loading the extension to see the problem I have mentioned above.
Hope this helps you experts resolving the issue.

I think this is the intended behaviour of ui-router. You might need to use native javascript for this one (window.location.href = 'XXX') or maybe $location to set the hashbang exactly like you want.

Ok, After so much of research and hit and trial.
here is the code that won't change the url when changing states.
I had to use html5Mode. More detailed info and usage can be found here.
https://docs.angularjs.org/guide/$location#html-link-rewriting
stackoverflow post
AngularJS 1.1.5 - automatically adding hash tag to URLs
angular
.module("app", ["ui.router", "app.services", "app.directives", "app.controllers"])
.config(["$stateProvider", "$locationProvider", function ($stateProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: true
}).hashPrefix("!")
}])
hope this helps, someone out there!

Related

How to dynamically set and Angular JS page's meta og tags for Facebook sharing?

This question is closely related to this one I asked a couple of days ago.
I am building an angularJS web-application. I am currently trying to use the ngMeta module to allow the web-app to produce dynamic entries for page title and for meta tags so that' Facebook will know to display an image, a title and description whenever a user posts a link from my web-app. I'm using Facebook's public-facing debugger to help me troubleshoot this.
But it is not working for me. Here is the state I'm using for my web-app's Splash Page:
$stateProvider.state('splash', {
url: '/',
templateUrl: 'html/splash.html',
controller: 'SplashCtrl',
data: {meta: {'title': 'XXXXXXXXXXXX',
'description': 'YYYYYYYYYYYY'}}});
Here is my controller:
myApp.controller('SplashCtrl', function($scope, ngMeta) {
var self = this;
console.log('self = ', self);
ngMeta.setTag('description', 'DDDDDDDD');
Here is my index.html
Here is my template file, splash.html which is referenced in the state declaration:
<div ng-controller="SplashCtrl as splashCtrl">
HELLO WORLD
</div>
Look what Facebook's debugger reports when I scrape this Splash Page (FYI, my private info has been scrubbed):
Why isn't the description I'm setting in SplashCtrl ('DDDDDDDD') showing up in Facebook's scraper? How can I fix it so it does?
BTW, I have successfully initialized ngMeta using the run() block. I know it's working because when I load this page, the <title>{{ngMeta.title}}</title> from index.html correctly shows up as AAAAA.
So ngMeta.setTitle() is definitely working. Then how do I set and access the other properties like description, image, etc?
All your meta tags are binding well, you can see it by inspecting your page
.
I think this facebook tools is reading the source code of your page instead of the initialised angular app(as if you do CTRL + U in chrome to see your source code, you will see that datas are not templating)
This does not matter for sharing content from your angular application. Facebook will take care to read the binding value instead of the scope variable
However if you want no scope variable from your source code,
This answer could be a solution

$locationProvider in angular url

Recently I have developed a website http://www.skduhariya.com, this is completely based on angularJS. I'm using the concept of ui-router for routing between the static pages. Symbol(#) is being displayed in the URL like skduhariya.com/#/blogs
I tried using $locationProvider to remove Symbol(#) from the URL so URL becomes like skduhariya.com/blogs,
its working fine, But, when we refresh the browser is not working as expected. Its display 404-Page Not found.
code:
function routeConfig($stateProvider, $locationProvider) {
$stateProvider.state('public', {
abstract: true,
templateUrl: 'src/public/public.html'
});
$locationProvider.html5Mode(true);
}
can anyone help me out to fix this.
You may could watch here
As he is already describing:
Server side
Using this mode requires URL rewriting on server side,
basically you have to rewrite all your links to entry point of your
application (e.g. index.html)
:)

Angular $location.path() and URL parameters

I'm struggling with Angular $location service... I am trying to redirect a user to this URL : "/test/0/0", and my route.js is configured with :
$routeProvider
.when ('/test/:param1/:param2',{
// Behavior here
})
When I simply do
$location.path('/test/0/0');
Angular seems not understand this path and can't associate it with the one I configured in the routes.
I have read about the $location service : I have tried $location.search(), .url(), but none of them works.
Any ideas would be welcome!
You could put a template and a controller to these route
.when('/page/:param1/:param2',{
templateUrl:'page.html',
controller: 'PageController'
})
I made an example to show you it running, you can check the code here.
First of all, I would like to thank you NEOLPAR for this piece of code which depicts accuratly what my problem was and seems to solve it perfectly. I tried to do what you suggest and unhopefuly it didn't work. But thanks a lot anyway!
As I was all out of ideas, I tried to replace $location.path() by a window.location.href directly, which also didn't work. This lead me to the conclusion that Angular just didn't bother reloading the page (because I didn't precise it but going to '/test/0/0' was just going to the current page). Thus I googled how to force a page reload and found a really nice solution (for my precise situation), which is to use :
$route.reload();
Thank you one more time for your help!

Angular routing without changing location

Chrome Packaged Apps have a rather strict Content Security Policy. One result of this is that manipulating the location (like clicking on a link) results in:
'Can't open same-window link to "chrome-extension://lkjasdfjklbdskjasdfjkhfdshjksad/derp.html"; try target="_blank". '
Target _blank will open the link in chrome which is not what I want. Can AngularJS' routing work in such a locked-down environment?
They docs give an example of an Angular app, but conspicuously does not use routing.
Update
Here is the link that, when clicked, gives the error: <a class='walrus-link' ng-href='paystubs/{{walrus.id}}'>Walrus {{id}}!</a>
Instead of using an href, try using ng-click and call a method to your controller the relocates to the appropriate page using $location. See the documentation on the AngularJS site. The following quote from the doc gives an indication that the $location service might be appropriate for you:
When should I use $location? Any time your application needs to react
to a change in the current URL or if you want to change the current
URL in the browser.
Your code might look something like this:
<a class='walrus-link' ng-click='getPaystub(walrus.id)'>Walrus {{id}}!</a>
and in your parent controller, you'll need a scope method called 'getPaystub' with a line similar to:
$scope.getPaystub = function(selectedWalrusId) {
$location.path('paystubs/'+$scope.walrus.id);
}
This way angular keeps control and won't cause a page refresh. This hopefully keeps you within the bounds of the CSP. Unfortunately I cannot test this in a packaged app, but I've used the exact same convention in a web app and it works just dandy.
routing works for me in my chrome app when not using $routeProvider's html5 mode (which is disabled by default), you just have to use a hash in the url.
so my links look like this:
About
$routeProvider configuration is as follows:
$routeProvider.when('/about', {templateUrl:'about.html'})

Force reload of a directive's template

I am working on an AngularJS app with several directives. The directive's templates are stored in a separate html file. When editing these template, my browser does not detect any changes after a reload and always uses a cached version. Any other changes to the source code are detected and lead to a reload.
I guess the problem is somewhat the $templateCache which seems to be used by AngularJS when loading the template.
What I found in the source code of AngularJS 1.0.2 is the following from line 4317 which is part of the compileTemplateUrl():
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache})
I am wondering if anyone else had this kind of problem and if there is a way to tell AngularJS when to cache and when not.
I know this is an old question, but here's a simpler fix, although it's a bit of a hack, it works for me, and doesn't require you to do anything to $templateCache.
Whenever I run into this problem (I see it in directive templates, but also static JSON files), I add a query parameter to the end of the URL being loaded, like this:
...
templateUrl: "partials/template.html?1",
...
Whenever I make a changes to the template, and it's not reloading, I increment that number at the end. As the browser doesn't know if this might mean something special to the server, it should attempt to reload that changed URL whether it's cached or not. This will also make sure the file is reloaded in the production environment.
The template cache is stored in your browser, as this is a javascript app. You can actually feed the $cache manually or stop your browser from caching the templates (as it would seem that for production, cache won't be a problem), using developer tools.
For force feeding the cache:
function Main($cache) {
$cache.data['first.html'] = {value: 'First template'};
$cache.data['second.html'] = {value: '<b>Second</b> template'};
}
Main.$inject = ['$xhr.cache'];​
See it working in this fiddle.
To stop your browser from caching the templates (cited from this Google Groups post, about this problem, exactly):
My team and I have ran into this same issue. Our solution for
development while using Chrome was to open Developer Tools, and select
the gear in the bottom right hand corner. Then select Network -
Disable cache.
This fixed all our partial/template caching issues.
app.controller('someCtrl', function ($scope, $cacheFactory, templateRequest)
{
$scope.refreshTemplate = function ()
{
var tpl = "<template name>";
$cacheFactory.get('templates').remove(tpl);
$templateRequest(tpl).then(function ok(){
console.log("Template "+tpl+" loaded.");
});
}
...
}
then when you call the refreshTemplate function you cause a re-load

Categories

Resources