I have been trying to get the url parameter in Angular, but this is not a Single Page application. I tried the below code snippet.
www.example.com?param1=ABC
Injected $location in controller, then
var paramValue= $location.search().param1;
In the above case, paramValue is undefined. But, If I change the url to
www.example.com#?param1=ABC (Added # in the URL) it works.
But, I don't want to do this because it breaks the page since it is not SPA.
Can someone suggest a better way to get the url parameter without using # in the url?
try this..
inject $stateParams into the contoller
var paramValue=$stateParams.param1
this will work in your scenario
Use this if you are not using stateParams:
this.$routerOnActivate = function(next) {
$scope.paramValue= next.params.param1;
};
First enable the html5 mode:
Add the following code in router:
app.config(["$locationProvider", function($locationProvider) {
$locationProvider.html5Mode(true);
}]);
Second, Then update the index.html
<head>
...
<base href="/">
</head>
Finally, Inject the $stateParams into the contoller and access using
following
var paramValue=$stateParams.param1
use $routeParams
In AngularJs in your $routeProvider
.when('/sample/:id',
{
templateUrl: 'sample.html',
controller: 'sampleController'
})
In your controller get it with $routeParams.id
Related
I have an app which creates several surveys with random survey ids. As the ids are generated in the backend they are set in the controller. I read the documentation on that, however I do not really understand how to set the routeparams in order to always reach the page /survey/:surveryID.
Here is my code so far:
App Config:
...
.when('/survey/:surveyId', {
templateUrl: 'views/survey.html',
controller: 'SurveyCtrl',
controllerAs: 'survey'
})
Controller:
function SurveyCtrl($scope, RequestService, _, $location, $routeParams) {
$scope.go = function () {
$location.path('/#/survey/' + Math.random());
};
}
View with the link to /survey/:surveyId:
<div>
<md-button ng-click="go()">Enter Survey</md-button>
</div>
I know that this is not the right way and it is not even working. Can someone tell me how to dynamically create these params and set them in the controller so I can access the link with a button and then when clicked reach the survey/:surveyId page?
To get your work done,
$location.path('/survey/' + Math.random());
You can use search method to pass params as well,
$location.path('/myURL/').search({param: 'value'});
$location methods are chainable.
this produce :
/myURL/?param=value
You could also use the updateParams method for that:
$route.updateParams({'surveryID': Math.random()});
And access the data using $routeParams.surveryID
In my angular project, when changing the path with $location.path('/foobar') the destination view is displayed but the data aren't reloaded (typically after saving an item and going back to the list, the list is not updated).
I tried to add $route.reload() or $scope.apply(), but nothing change.
I don't know what's wrong or missing to make this work.
UPDATE
$location.url() doesnt' work either
I'm using angular 1.2.26
UPDATE 2 - ANSWER
Ok, after a lot of comments and answers, I think it's time to end this.
I didn't think it would have been a so complicated question.
So, my conclusion, giving all you said is :
Giving simple example of #yvesmancera, the default behavior of the controller is to reload itself
In a complex controller with a resource factory and some REST calls, any save or update action should also manually update the list reference, or trigger a full reload of the list
All of you gave me some good advices, so thank you.
Use $window.location.href. to reload the page. I just check on $location document:
Page reload navigation
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.
Example:
$window.location.href = "/your/path/here";
I had the same problem just yesterday, if you try to navigate to the same path you're already in, angular won't try to reload the view and controller. What fixed it for me is appending a "/" at the end of each route in $routeProvider, e.g:
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/About/', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/Contact/', {
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
})
Edit
Here is a working plunkr with angular 1.2.26
http://plnkr.co/edit/jkGKKCp0djN6Jvy2fIRd?p=preview
Pseudo Code:-
app.controller('myController', ['$scope', '$location','$http', 'ItemListService'
function($scope, $location, $http, ItemListService){
$scope.data = function(){
ItemListService.getAllItems(); //get all the items;
};
$scope.saveMethod = function(item){
$scope.data = ItemListService.save(item); //this is the refresh part, return data through save method. Pull the latest data and bind it to the scope.
$location.path('/fooView'); //dont think you even need this if you are entering data in a modal sorta thing, which on the same view.
}
}]);
You service should look like,
app.service('ItemListService', function(){
this.getAllItems = function(){
//get the items from itemList
//return all the items
}
this.save = function(item){
//save the item in itemList
//**return all items again, call getAllItems here too.
}
});
Hope this helps!!
You can switch https://github.com/angular-ui/ui-router it has method $state.reload() which can re-initialize whole controller.
If you dont want to switch ther is problem that controller is still living but you can implement after save
$rootScope.$broadcast('data:updated', $scope.data);
then wrap method of loading data in controller to function and then you can push new data to existing list / or make ajax reload
$rootScope.$on('data:updated',function(listener,data) {
$scope.data.push(data);
});
$rootScope.$on('data:updated',function()
{
callAjax.then(function(data) {
$scope.data = data;
}
});
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$on
Try $scope.dataModel.$save(); $location.url('/foobar'); Another reason might solve the problem is: when you redirect to /foobar, the controller of foobar should have a AJAX call to your server to load the new data. And you should use angular factory to make your AJAX calls. If it is still not working, can you give more information about the version of the angular you are using, as well as your backend framework and database.
$location.path("/login");
$timeout(() => $scope.$apply(), 1000);
works for me
I have a AngularJS Application in different languages.
Now I want to preselect a language, when the user calls the site, with following string at the end:
/en, /de, ...
Is this even possible in AngularJS? I also can use some other syntax, if this is needed.
Thank you very much!
If you are wanting to get something from the url to run logic on (i.e. /de in the url)
you can use the $location object
Angular location
If you are wanting dynamic urls so that things like /de, /fr, /es go to the same page/view, you'll need to use the $route object
Angular routes
With the limited amount I could understand from your question..
var app=angular.module("angularapp",['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',{
redirectTo: '/en'
})
.when('/:language',{
//do something
});
}]);
you can then get access to {"language":"en"} object
It's the first time I'm trying to use the $location service in AngularJS in order to check for query string arguments. I've been reading the docs and trying to play a bit with it in Plunkr to see how to use it, but so far I've failed to get it to retrieve any parameters from the query string.
I've been testing it using this plunk http://plnkr.co/edit/RIFdWa5ay2gmRa6Zw4gm?p=info
var app = angular.module('myApp', [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true);
});
angular.module('myApp').controller('myCtrl', function($scope, $location){
$scope.name = "Andrei";
$scope.url = $location.host();
$scope.path = $location.path();
$scope._params = $location.search();
});
I've read that setting html5Mode(true) on the $locationProvider is required in order to get the $location service to work as "expected" - which I've done, but when setting this nothing works anymore in my plunk (you can set it to false and you'll see the binding are qorking again properly).
Am I missing something regarding the $location service?
Any help or suggestions are appreciated!
Thanks!
In AngualarJS 1.3 $location in HTML5 mode requires a <base> tag to be present so that it knows the path that all of the links are relative to. You can add <base href="/" /> to get it working again.
http://plnkr.co/edit/j9rd1PajNLQVJ8r4c8BZ?p=preview
I'm having trouble transitioning to another view state when I only have the full URL path. The ui-router says to use $state.transitionTo or $state.go but those require the state name.
I tried to change the current URL using $location.url(path) but nothing happens.
Is $location.url(path) the correct way, and something is wrong with my setup or is there another way to do it?
Here is my configuration for the home page:
$stateProvider.state(
{
name: 'home',
url: '^/',
templateUrl: "/home.html"
}
);
Here is my config for the app.
cgTag.App.Config.Config = function($httpProvider, $locationProvider, $sce)
{
// Let CakePHP see $http requests as AJAX
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// use HTML5 non-hash URLs
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
// add all the CDN domains to the white list so that URLs are not blocked by Angular.
var cdn = cgTag.AppData["Domain"].replace(/^www\./, "http://s*.") + "/**";
$sce.resourceUrlWhitelist(['self', cdn]);
};
cgTag.Angular.config(['$httpProvider', '$locationProvider', '$sceDelegateProvider', cgTag.App.Config.Config]);
If the current browser url is http://www.cgtag.com/movies then calling $location.url("/") should go to the home page, but nothing happens.
I needed to call $scope.$apply() after calling $location.url(path).
Could be because the code was in a keydown event handler.
you need to use $location.path() instead $location.url()