i have used $routeProvide to redirect page from one page to another and in that i am passing some dynamic parameters in url.
it working at one place and not working with another place.
my code : in app.js
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: "client/home/home.html",
controller: "IndexCtrl",
access: {
isloggedIn: false
}
})
.when('/test/:searchTerm', {
templateUrl: "client/test.html",
controller: "testController",
access: {
isloggedIn: false
}
})
.when('/test2/:id', {
templateUrl: "client/index.html",
controller: "indexController",
access: {
isloggedIn: true
}
})
.otherwise({
redirectTo: "/"
});
}]);
in controllers file : for testController when i hit url
server.com/#/test/45 got in console 45 and for indexController when i hit url server.com/#/test2/45 then i get :id in console.
app.controller("testController", ['$location', '$rootScope', '$routeParams', function ($location, $rootScope, $routeParams) {
console.log($routeParams.searchTerm); //get result 45
}]);
app.controller("indexController", ['$location', '$rootScope', '$routeParams', function ($location, $rootScope, $routeParams) {
console.log($routeParams.id); //get result :id
}]);
why this happen can anyone help? and what should be the issue?
Try ($routeParams.id); instead of ($routParams.id);, I don't know why your $routParams.searchTerm is working, but it shouldn't (should be route, not rout).
Seems like your code is correct, other than the spelling mistake. The only difference i can find is that the IsLoggedIn property value. Did you try by making it false?. And what is the significance of IsLoggedIn property.
check your hyperlink to the route /test2/:id.
It may be like ng-href="#/test2/:id"
change it to ng-href="#/test2/{{id}}"
don't forgot to define variable id
recreated the issue in fiddle
Related
Working on single page application everything is working fine but getting stuck when want to set 404 page when :username not found or any unexpected url will load in browser please check my code below
controller.js
var myApp = angular.module('assignment', ['ngRoute']);
myApp.service('userData', ['$http', function($http){
return{
userslist : function(){
return $http({'url' : 'js/data.json', 'method' : 'GET'}).then(function(response){
return response.data;
}, function(data){
console.log('some error')
})
}
}
}]);
myApp.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'user-list.html',
controller: 'users'
}).
when('/:username', {
templateUrl: 'detail.html',
controller: 'userdetail'
}).
otherwise({
redirectTo: '/404.html' /*>>>>>>Here is the problem<<<<<<*/
});
});
myApp.controller('userdetail', ['$scope', '$routeParams', 'userData', function($scope, $routeParams, userData){
var selectedUser = $routeParams.username;
selectedUser = selectedUser.replace(/-/g, ' ');
userData.userslist().then(function(data){
$scope.items = [];
angular.forEach(data.data.bst_users, function(item){
if(item.name == selectedUser) {
$scope.user = item;
};
})
})
}])
myApp.controller('userdetail', ['$scope', '$routeParams', 'userData', function($scope, $routeParams, userData){
console.log($routeParams.username);
userData.find($routeParams.username, function(found){
$scope.user = found;
})
console.log(scope.user)
}])
/*******Filters*******/
myApp.filter('removeSpace',function() {
return function(input) {
if (input) {
return input.replace(/\s+/g, '-');
}
}
});
Since you declared /:username as a route, it can match anything after the /, meaning the 404 route isn't really doing anything and the username route in a sense is acting as your catch-all route. This is kind of a weird case, since you can't really define a regular 404 route. But what you could do is have a /404 route, then if /:username doesn't resolve to a user, redirect them to /404. That is the most efficient method I can come up with, but I guarantee there's a better way to do it.
#Jordan points out a definite issue.
I would recommend updating your user detail path to something like the following:
when('/user/:username', {
templateUrl: 'detail.html',
controller: 'userdetail'
})
Just so there is no confusion between /random_username and /unmatched_path.
I am using angularJs for my webApp, but i used $stateProvider everywhere to define state.so now I want to use $routeProvider instead of $stateProvider.and how I change the route? is $location is good to change the path ?
This is my trial code with $routeProvider
angular.module("angular.states", [])
.config(['$routeProvider', '$locationProvider', '$stateProvider'], function ($stateProvider, templateRoot, $routeProvider) {
$routeProvider.when('/login?username&message&error', {
'templateUrl': '/templates/login.html',
'controller': 'LoginController'
});
$routeProvider.when('/logout', {
'templateUrl': '/templates/logout.html',
'controller': 'LogoutController'
});
})
.controller('LoginController', function (UserService, $scope, $state, $stateParams, AuthFactory, $timeout, $location) {
$scope.login = function (username, password) {
UserService.login({
'username': username,
'password': password
});
};
})
.controller('LogoutController', function (UserService, $scope, $location) {
$scope.logout = function () {
UserService.logout({}, function () {
$location.path("/login", {
});
});
};
});
I am not sure about $routeProvider, so please tell me how to use it
You should use $stateProvider instead of $routeProvider. because you can easily change your state using $stateProvider.
& if you use $routeProvider you need to use location, path, its url & all,
You cannot relate to routes with each other like who is parent and who is child.
so $stateProvider is always better to use.
Using $stateProvider :
$stateProvider.state('login', {
'url': '/login
'templateUrl': '/templates/login.html',
'controller': 'LoginController'
});
here you can simply change your state with given url you dont need to locate the path.
I would like preserve instance of controller without reloading. I set reloadOnSearch to false and I manage route change in my controller. Here is the code.
This is example of my link next. I have defined following module.
angular.module('app.products', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/:section/:view/:number', {
templateUrl: 'tpl/table.html',
controller: 'ProductsCtrl',
controllerAs: 'productsCtrl',
reloadOnSearch: false
});
}])
.controller('ProductsCtrl', ['$scope', '$routeParams', '$location', ProductsCtrl]);
Controller
function ProductsCtrl($scope, $routeParams, $location) {
$scope.$on('$routeUpdate', function () {
console.log("routeUpdate");
});
}
But the controller doesn't respond on changed route and text is not written to console output.
In the angular jargon, "search" refers only to the query string parameters part of the URL. For instance: ?key=value&page=42
And the "path" refers to the URL without that query string. Here /products/page/2 is a path.
When setting reloadOnSearch: false you're telling angular not to reload the view and the associated controller when only the query string parameters changes.
So if the path changes, for instance you navigate from /products/page/2 to /products/page/3, then the view will still be reloaded. No $routeUpdate will be fired because there is no need for that. You'll get the new parameters from $routeParams when your controller initialization function is called again.
However if the path doesn't change, but only the query string parameters do change. For instance when you navigate from /products?page=2 to /products?page=3. Then the view will not be reloaded and a $routeUpdate will be broadcast.
So the solution here would be to define page as a query string parameter instead of a path parameter:
angular.module('app.products', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/:section', {
templateUrl: 'tpl/table.html',
controller: 'ProductsCtrl',
controllerAs: 'productsCtrl',
reloadOnSearch: false
});
}])
.controller('ProductsCtrl', ['$scope', '$routeParams', '$location', ProductsCtrl]);
Controller:
function ProductsCtrl($scope, $routeParams, $location) {
$scope.setupView = function setupView(section, page) {
// Setup you view here
// ...
};
$scope.$on('$routeUpdate', function () {
// This is called when only the query parameters change. E.g.: ?page=2
$scope.setupView($routeParams.section, $routeParams.page)
});
// This one is called when the the path changes and the view is reloaded.
$scope.setupView($routeParams.section, $routeParams.page)
}
Instead of $routeUpdate, try to use $routeChangeSuccess.
$scope.$on('$routeChangeSuccess', function (scope, next, current) {
console.log("Your text goes here.");
});
You can use next and current to check your previous and next route.
Hope it helps.
I am trying to take advantage of the back button's history, and so I am using the traditional $routeProvider and a url of
.../arg1/something/arg2/something,else/arg3/another/arg4/yet,another/arg5/final
However, if one argument is missing, the following route provider will fail to pass the remaining arguments to the $routeParams:
angular.module('myApp', [ … ])
.config(function ($routeProvider) {
$routeProvider
.when('/arg1/:args1/arg2/:args2/arg3/:args3/arg4/:args4/arg5/:args5', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
});
});
How do I configure the $routeProvider to pass the arguments that are present, (in any order if possible, if not at least in the order that but account for absence of an argument), to the controller without having to declare all 720 (6!) different scenarios of different arguments in different order or not at all?
I then plan to use these values to populate the filters in the controller via the following:
function filterRouteParams (rp){
if(rp.args1){
$scope.args1 = rp.args1;
}
if(rp.args2){
$scope.args2 = rp.args2.split(',');
}
if(rp.args3){
$scope.args3 = rp.args3.split(',');
}
…
}
I am a little familiar with using the ? query on the URL, but to my knowledge, I don't know how to bind that to the history when I want to update it and also allow for using the back button and maintain the query, but am open to being schooled!
Do I not understand ur question, or it just got complicated?
You just SIMPLY use query string for this purpose.
It works perfectly fine with back and forward buttons, history push/state.
angular.module('myApp', ['ngRoute'])
.controller('MainController', function($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})
.controller('FilterController', function($scope, $routeParams) {
})
.config(function($routeProvider) {
$routeProvider
.when('/filter', {
template: 'inside filter',
controller: 'FilterController'
})
.otherwise({
redirectTo: '/filter'
});
});
This is the running example of the above code, http://run.plnkr.co/plunks/OS38E38J11FeDS1hyHde/#/filter?c=3&d=4
and Here is the plnkr.
I think the best way of handling this is through query string parameters, so your route is defined like this:
.when('/filter', {
controller: 'MainController'
})
And you just use a URL like /filter?foo=44&bar=123&baz=true, or in code:
$location.path('/filter').search('foo', $scope.fooValue).search('bar', $scope.barValue);
Parameters are optional and be specified in any order as ngRoute does not do any validation of param names or values.
To access the values in your controller:
.controller('MainController', function($scope, $routeParams) {
if ($routeParams.foo) {
// do argument processing
}
})
docs for $routeParams: https://docs.angularjs.org/api/ngRoute/service/$routeParams
I'm not sure to really understand, but could you use '?' inside your routes ? for example
$routeProvider
.when('/arg1/:args1?/arg2/:args2?/arg3/:args3?/arg4/:args4?/arg5/:args5?', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
});
Any of the following URL would be valid
/arg1/arg2/arg3/arg4/arg5
/arg1/value1/arg2/arg3/arg4/arg5/value5
....
/arg1/value1/arg2/value2/arg3/value3/arg4/value4/arg5/value5
Is that what you were looking for?
Unfortunately I couldn't find a way to remove an argument like this
/arg1/arg2/arg4/value4/arg5/value5
I'm pretty new to AngularJS,- in my AngularJS app I have a check in my AppCtrl controller if we have to redirect or not.
.controller('AppCtrl', function($scope, $location) {
if(window.localStorage.getItem("lastStation")) {
$location.path('/app/player/'+window.localStorage.getItem("lastStation"));
}
....
.controller('PlayerCtrl', function($scope, $stateParams) {
alert($stateParams); // This one is alerted TWICE if the $location.path is called in the AppCtrl controller
Hope someone can help with that! ;)
You must have configured routing for your application, like:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/app/player/:lastLocation', {
templateUrl: 'path_to_your_view',
controller: 'PlayerCtrl'
}).
.....
}]);
Now I got it ;)
.run(function($rootScope, $location) {
if(window.localStorage.getItem("lastStation")) {
$location.path('/app/player/'+window.localStorage.getItem("lastStation"));
}
});
I had to make the check in a .run method.