Update $routeParams and refresh the page with new parameter - angularjs

I think the title indicates what I want to achieve quite well. As an example, say, I have a route parameter:
$routeProvider.when("/:id/page", {
controller: "pageCtrl",
templateUrl: "page.html"
});
And in the controller, I want to change it and refresh the page. Is there such a way? For example:
$routeParams.id=12;
$route.reload();
Thanks for any help in advance...
Note:
Currently I use this way:
var pathArray = $location.path().split("/");
pathArray[1] = 12;
$location.path(pathArray.join("/"));
But I'm looking for a more generic way.

Related

Providing variables outside of ng-view

So, I have an HTML page, /profile#IDGoesHere which is tied an an ng-app. The ng-app has three columns (with Bootstrap) and the middle of which is utilising Angular's ng-view.
So it's something like this:
/profile#IDGoesHere (and within it):
All Activity
Posts
Likes
Dislikes
etc
The href links are set on the HTML page outside of the ng-view so when I go into the /profile#IDGoesHere page, I set the userID into a variable using a service. Like below:
profileApp.service('globalParams', function() {
var profileID = '';
var user = {};
return {
getProfileID: function() {
return profileID;
},
setProfileID: function(value) {
profileID = value;
}
};
});
I pass the 'globalParams' service into each controller as I need to access the profileID in order to make further calls to get the specific data for the user.
My Angular Router looks like this:
$routeProvider
.when('/profile:id', {
templateUrl : 'partial/profile/feed.html',
controller : 'mainController',
resolve:{
myData: ['$http', function($http){
return $http.get('/session');
}]
}
})
.when('/posts', {templateUrl: 'partial/profile/posts.html', controller: 'postsController'})
.when('/agreed', {templateUrl: 'partial/profile/likes.html', controller: 'likesController'})
.when('/disagreed', {templateUrl: 'partial/profile/dislikes.html', controller: 'dislikesController'})
.when('/comments', {templateUrl: 'partial/profile/comments.html', controller: 'commentsController'});
});
Now the problem, the links to Posts, Likes, Dislikes etc do not have the profileID in them as they are set when you go to the main route, /profile#IDGoesHere.
This works when I am on the page and keep navigating by using the 'globalParams' service however, if I were to refresh the page when I was on one of the sub-pages, the data is lost.
Note: I can't make the whole page to reload which is why I used the ng-view. I could fix this by doing that but it will defeat the purpose of a single page application.
Does anyone have a good idea on this? Been pulling my hair but feel I am missing something very obvious.
Thanks in advance
Edit: as it was causing some confusion, I have added a screenshot to demonstrate how it looks like:
Got it fixed by attaching the whole < body > to a parent controller and under that controller, I used the $window.location.href and split the ID from URL and then added it to the service, which I could then add to the outer hrefs for my sub-pages, essentially making the sub-pages to have a routeParam as well

Angular.js: hide a div from my index file when viewing any one of multiple partials

I'm hoping that this question isn't going to get me punched in the head but as I'm this (holds fingers closely together) far from punching myself in the head I figured I'd go ahead, swallow my pride and ask anyway.
As a self confessed Angular newbie I'm having an issue hiding a div on my index file (which is my layout page) when a visitor calls specific partials to that page.
I have around 55 partials (scope creep is a wonderful thing) and the offending div should not appear on 12 of them.
Here is my markup:
<div ng-show="somename" id="somename" ng-controller="somenameCtrl">
<div ng-include="'templates/somename.html'"></div>
</div>
and here is my controller:
app.controller('somenameCtrl', function($scope, $route, $location) {
$scope.$on('$routeChangeSuccess', function() {
var path = $location.path();
console.log(path);
$scope.somename = true;
if (path === '/thatpage') {
$scope.somename = true;
} else if (path === '/thispage') {
$scope.somename = false;
}
});
});
I figured that this would be the simplest way forward, but now I'm less convinced as (as previously stated) I have several partials to hide the div from the index file. Obviously the div is not showing on 'thispage', and is showing correctly on 'thatpage' (and where any partial other than 'thispage' is called.
However, I need to not show the div on pages 'thispage2' -> 'thispage12' and keep it shown on everything else. Any idea on how I can achieve this?
Any help would be gratefully appreciated - if there's anything unclear, please do let me know and I'll try my best to give greater clarity.
There are many ways of doing this in Angular. Too many.
I'm assuming you use ui-router or ng-router. Both routers have a resolve method in them. In each route/state you define, you can pass in the SomeName variable like so:
.when('/someRoute', {
templateUrl: '...',
controller: '...',
resolve: {
SomeName: false;
}
})
And then include this in your controller:
.controller(function(SomeName, $scope) {
$scope.somename = SomeName || false;
}
This way, you need to define the SomeName variable only in the routes where it's true. It would default to false when not defined, so you won't need to define it on every route
Of course, there are other methods of doing this as well, but this seems to me like the cleanest method

Passing parameters with ui-router in URL

Hi i'm trying to pass a parameter from page A to B.let's say you get a name from user in page A and want to show it in page B.
I Googled a lot but there is not a working result so i can see how all parts work together.
Q :I know i need to use $stateParams here but how it's unclear for me.
Thanks is advance.
Below is an example of state params being used:
var app = angular.module('app', [])
app.config(function($stateProvider){
$stateProvider
.state('sample', {
url: '/sample/:name',
templateUrl: '.sampleView.html',
controller: 'SampleController'
})
app.controller('SampleController', function($stateParams) {
//access params by using $stateParams.<param name>
var name = $stateParams.name;
}
The scenario you described sounds more like something where you would want to use a factory/service or maybe even some browser caching.

Passing url query string value to a view template in angular route

I am new to AngularJS. I am trying to rewrite my site that use JQuery.
In my existing site I use
$(document).on("click",".movieposter",function(){
window.open("moviedetail.html?id="+this.id);
}); to open a detail page of current page.
I am trying to use AngularJS route to get same function. I did my research, but I cold not figure out how to do it. I am stuck in following code.
.state('moviedetail', {
url: "/moviedetail?id",
templateUrl: "views/moviedetail.html",
controller: function ($stateParams) {
alert($stateParams.id); //*** Exists! ***//
}
})
I got url that has id of a movie that is going to use to get movie detail information. How can I pass that movie id to view template that will display detail view. Thanks in advance.
Use state params to pass an object.
ui-sref="movielist({movie: movieDetails})"
Thanks for your answers Vinay and charlietfl. I learned some new knowledge by doing research based on your answer. Using state params to pass an object is a good idea. And I found out about resolve statement too. Nevertheless, I decided to use localStorage instead of passing an object as parameter. I only use state param to pass id of a movie.
Here is html:
<a class="moreInfo" ng-click="save({{movie}})" ui-sref="moviedetail({id: {{movie.id}}})"> Find Out More </a>
Here is save method in movie controller:
$scope.save = function (movie) {
localStorage.setItem(movie.id, JSON.stringify(movie));
}
Here is how I get data in MovieDetail Controller:
var movie = JSON.parse(localStorage.getItem(id));

Don't reload the ngView template when I change a parameter with $location.search()

I posted a question recently about how to set parameters in the URL with Angularjs so that they could be preserved on page reload. But it caused a problem with Google Maps.
I am using ngRoute to navigate around my application. And the problem that I've experienced with setting parameters in the URL, was that every time I would set a parameter (be it $location.search() or just a plain old window.location.hash='something'), the Google Maps map would get unloaded. I tried changing parameter names, because I thought Google Maps listens to some of those options by default. But that wasn't the case.
Once I got rid of the ngRoute code completely, and instead of the ngView directive, I included my pages with ng-include, the map didn't get unloaded anymore when I manipulated the parameters.
I'm not that good as to know exactly what or why is going on, but I would guess that ngRoute thinks it has to compile my template file again because "something" changed in the URL. So what I would like, is to explain to ngRoute somehow, that if the part after ? changed, then it shouldn't try to compile my template file again (and subsequently destroy the loaded Google Maps), because those are just my additional options. But if the part before ? changed, then that's fine, because then the page changed.
Or, is there another, better, more Angular-way of getting around this issue?
This is my ngRoute configuration:
app.config(function($httpProvider, $routeProvider) {
// Routing
$routeProvider.when("/", {
redirectTo: "/Map"
}).when("/Map", {
controller: "MapController",
templateUrl: "tpl/view/map.html"
}).when("/Table", {
controller: "TableController",
templateUrl: "tpl/view/items-table.html"
}).otherwise({
templateUrl: "tpl/view/404.html"
});
});
This is my code for changing pages:
$scope.navigate = function(location) {
$location.path(location);
};
And this is how I would set up a custom GET parameter, as per the code from my other Stackoverflow question:
var params = $location.search();
params.source = source.filename;
$location.search(params);
You're looking for the reloadOnSearch property.
app.config(function($httpProvider, $routeProvider) {
...
}).when("/Map", {
controller: "MapController",
templateUrl: "tpl/view/map.html",
reloadOnSearch: false
})
...
});
https://docs.angularjs.org/api/ngRoute/provider/$routeProvider

Resources