How to get id from url()This is my url
http://localhost:59113/Project/EditProject?id=2
I did it using jquery..
var url = document.URL;
var id = /id=([^&]+)/.exec(url)[1];
var result = id ? id : ' ';
But I need to do it using angular.Can anyone help me?I tried this too(updated part)
var app = angular
.module("intranet_App", [])
app.config("$routeProvider", function ($routeProvider) {
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'Project/EditProject.html',
controller: 'myCtrl'
})
})
.controller("myCtrl", ["$scope", "$http", "$location", "$route", function ($scope, $http, $location, $route) {
// alert($location.id)
var a = $route.current.params;
alert(a.id)
}])
Using $routeParams you can get id,
Updated answer
Use $route instead of $routeParams. Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.
$route.current.params
EDIT
You must do this in .config() method
app.config(function($routeProvider){
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'Project/EditProject.html',
controller: 'myCtrl'
})
})
$location.search() returns an object, so as per above url
http://localhost:59113/Project/EditProject?id=2
$location.search().id will fetch you an answer.
More Info:
If you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy, To fix this you need to change the following in config file
$locationProvider.html5Mode(true);
$location.search() will return an object of key-value pairs.
in your case:You could access this value directly with $location.search().id
Related
I need to setup a controller with some data passed from the routeProvider.
I would like the value topic to be passed to my controller VideoCtrl and then assigned to a value such as video.topic
$routeProvider
.when('/video/:topic', {
templateUrl: 'pages/video/video-page.tmpl.html',
controller: 'VideoCtrl',
controllerAs: 'video'
});
It seems like I should just need to call $routeProvider in my controller function:
app.controller('VideoCtrl', function($routeProvider) {
var video = this;
video.topic = $routeProvider.topic; // What do I need to add here?
...
});
But I can't seem to figure out how to inject $routeProvider into the controller.
I think, you need to pass the $routeParams as controller parameter and then you will able to get the passed route value.
app.controller('VideoCtrl', function($routeParams) {
var video = this;
video.topic = $routeParams.topic;
...
});
I have multiple clients on my angular app and I want to create different themes inside angular (only the visual part will change, controllers remain the same.
I have a "security" module which manages the authentication, currentLoggedIn user and so on.
var security = angular.module('security', ['ui.router'])
// .factory('authService', authService);
.service('authService', ['$http', '$q', '$window', 'CONSTANTS', '$location', 'currentUser', '$state', '$rootScope', authService])
.factory('authCheck', ['$rootScope', '$state', 'authService', securityAuthorization])
and authService is basically having these methods/values
service.login = _login;
service.logout = _logout;
service.reset = _reset;
service.isAuthenticated = _isAuthenticated;
service.requestCurrentUser = _requestCurrentUser;
service.returnCurrentUser = _returnCurrentUser;
service.hasRoleAccess = _hasRoleAccess;
How can I get access to currentUser inside templateURL function to modify the URL based on data for currentUser?
AuthService and AuthCheck are empty when accessed in templateURL function.
$stateProvider
.state('home', {
url: '/home',
templateUrl: function(authService, authCheck) {
console.log (authService, authCheck);
return 'components/home/home.html'
},
data: {
roles: ['Admin']
},
resolve: {
"authorize": ['authCheck', function(authCheck) {
return authCheck.authorize();
}],
"loadedData": ['metricsFactory', 'campaignFactory', '$q', '$rootScope', 'selectedDates', loadHomeController]
},
controller: 'HomeController',
controllerAs: 'home'
});
In case, we want to do some "magic" before returning the template... we should use templateProvider. Check this Q & A:
Trying to Dynamically set a templateUrl in controller based on constant
Because template:... could be either string or function like this (check the doc:)
$stateProvider
template
html template as a string or a function that returns an html template
as a string which should be used by the uiView directives. This
property takes precedence over templateUrl.
If template is a function, it will be called with the following
parameters:
{array.} - state parameters extracted from the current
$location.path() by applying the current state
template: function(params) {
return "<h1>generated template</h1>"; }
While with templateProvider we can get anything injected e.g. the great improvement in angular $templateRequest. Check this answer and its plunker
templateProvider: function(CONFIG, $templateRequest) {
console.log('in templateUrl ' + CONFIG.codeCampType);
var templateName = 'index5templateB.html';
if (CONFIG.codeCampType === "svcc") {
templateName = 'index5templateA.html';
}
return $templateRequest(templateName);
},
From the documentation:
templateUrl (optional)
path or function that returns a path to an html template that should be used by uiView.
If templateUrl is a function, it will be called with the following parameters:
{array.<object>} - state parameters extracted from the current $location.path() by applying the current state
So, clearly, you can't inject services to the templateUrl function.
But right after, the documentation also says:
templateProvider (optional)
function
Provider function that returns HTML content string.
templateProvider:
function(MyTemplateService, params) {
return MyTemplateService.getTemplate(params.pageId);
}
Which allows doing what you want.
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 building a rather simple AngularJS app, but for simplicity's sake, I'd rather not use the routing (if possible), and just serve back individual Angular pages from the server. Essentially, use Angular only for layout and functionality of 'widgets' and not for moving between pages.
With that said, I've spent hours trying to get an ID out of the current URL, so:
/Tickets/:id
All I want to do in my controller, is get the ID from the URL, then pass that to a Factory. (below is an example using pseudocode)
app.controller('ticketController', ['$scope', '$route',
function ($scope, $route, $location) {
//Get ID out of current URL
var currentId = someFunction().id;
factory.callFactory(ID);
}]);
I've also tried creating routes, but the objects returned don't seem to provide a way to get the ID.
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/tickets/:id',
{
templateUrl: '/partials/edit',
controller: 'ticketController'
}
);
}]);
Not sure what I'm doing wrong.
This doesn't seem to work for me
This also doesn't seem to work, but I may be doing something wrong
Try $routeParams instead:
app.controller('ticketController', ['$scope', '$routeParams',
function ($scope, $routeParams) {
//Get ID out of current URL
var currentId = $routeParams.id;
}]);
If you are using ui-router so try $stateParams:
app.controller('ticketController', ['$scope', '$stateParams',
function ($scope, $stateParams) {
//Get ID out of current URL
var currentId = $stateParams.id;
}]);
use url ~/list/result/1256
my code in one file
App.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/list/result/:param", {
controller: "ListController"
});
}]);
App.controller("ListController", ["$scope", "$routeParams", "$http", function ($scope, $routeParams, $http) {
I want to get "1256" here, but $routeParams - empty, why, what am I doing wrong
});
First of all, your question is incomplete. You have not posted the partial that loads when you navigate to the URL "/list/result/1256", i.e. your templateUrl is missing.
Secondly, you have not posted how you are trying to extract the param in ListController.
Per my knowledge,
var param = parseInt($routeParams['param'], 10);
should help you extract the param.