angularjs routes and param and controller - angularjs

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.

Related

Get Id from url() in angular

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

$routeParams.value is undefined when passing to new controller

I'm trying to pass a value from one controller to another. Using $routeParams as the method for doing this.
My main app references:
var app = angular.module('acnApp', ['ngResource', 'ngRoute'])
To pass the value:
//GO TO EDIT
$scope.getOrgDetails = function (orgId) {
console.log(orgId)
$location.path('/network_org/edit/' + orgId)
}
In my routes.js:
$routeProvider.when('/network_org/edit/:acnId', {
templateUrl: 'Pages/acn/orgs/network_org_edit.html',
controller: 'orgUpdateController'
});
On the receiving controller:
app.controller('orgUpdateController', ['$scope', '$location', '$routeParams', function ($scope, $location, $routeParams) {
console.log($routeParams.orgId)}]);
When I run this, the console result is "undefined"
Any help appreciated.
Try the method "url" rather than "path".
like this :
$location.url('/network_org/edit?orgId=' + orgId)
It should be :
console.log($routeParams.acnId)
instead of orgId because you are defining the id with acnId.
The formal parameter name you defined in your routes.js is called acnId. So try:
console.log($routeParams.acnId);

How to pass param in routeProvider in Angular JS?

I use routeProvider in Angular JS:
.when('/profile/personal', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
How I can pass param to controller EditProfileController and here call Ajax method that returns data. This data must be display in template of route in personal.html.
Example:
.controller('EditProfileController', ['$scope', '$http', function ($scope, $http) {
// If was click on `/profile/personal` from route, must get patam `personal` and call method GetAjax(param);
$scope.GetAjax = function (param){
//here return data put it in template HTML from route
}
}]);
My links are located in page by path:
http://wd.tk/profile
When I click to link route I get URL:
http://wd.tk/profile#/profile/personal/1
Id do:
.controller('EditProfileController', ['$scope', '$http', function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);
I get error:
TypeError: Cannot read property 'idProfile' of undefined
First, in your url configuration, you must put the parameter of url:
when('/profile/personal/:idProfile', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
Now, in your EditProfileController, you should get the parameter and call to ajax request:
Inject the $routeParams object and get the parameter with
$routeParams.idProfile:
.controller('EditProfileController',
function ($scope, $http, $routeParams) {
var idProfile = $routeParams.idProfile;
$http.get("service url").then(setData, setError);
function setData(data) {
$scope.data = data;
}
function setError() {
alert("error on get data profile");
}
}]);
In your html, you will show your data profile in the correct format.
But I recommend that all the ajax calls should groups in angular services.
PD:
Check It out angular ui router:
What is the difference between angular-route and angular-ui-router?
hope this helps.
You you need to change your $routeProvider, that should have /profile/:type instead of /profile/personal that means you are going to provide value for :type which can be accessible by injectin $routeParams service inside controller.
.when('/profile/:type', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
Controller
.controller('EditProfileController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$scope.profileType = $routeParams.type;
$scope.GetAjax = function (){
//here you have profile type in $scope.profileType
//you can pass it to ajax by simply accessing scope variable.
$http.get('/getprofiledata?type='+ $scope.profileType)
.success(function(data){
$scope.profileData = data;
})
.error(function(error){
console.log('error occured')
})
}
$scope.GetAjax(); //calling it on controller init
}]);
Update
YOu had missed one of dependency $routeParams in array annotation.
.controller('EditProfileController', ['$scope', '$http', '$routeParams',function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);

Angular Ui-router can't access $stateParams inside my controller

I am very beginner in Angular.js, I am using the Ui-router framework for routing.
I can make it work upto where I have no parameters in the url. But now I am trying to build a detailed view of a product for which I need to pass the product id into the url.
I did it by reading the tutorials and followed all the methods. In the tutorial they used resolve to fetch the data and then load the controller but I just need to send in the parameters into the controllers directly and then fetch the data from there. My code looks like below. when I try to access the $stateParams inside the controller it is empty. I am not even sure about whether the controller is called or not.
The code looks like below.
(function(){
"use strict";
var app = angular.module("productManagement",
["common.services","ui.router"]);
app.config(["$stateProvider","$urlRouterProvider",function($stateProvider,$urlRouterProvider)
{
//default
$urlRouterProvider.otherwise("/");
$stateProvider
//home
.state("home",{
url:"/",
templateUrl:"app/welcome.html"
})
//products
.state("productList",{
url:"/products",
templateUrl:"app/products/productListView.html",
controller:"ProductController as vm"
})
//Edit product
.state('ProductEdit',{
url:"/products/edit/:productId",
templateUrl:"app/products/productEdit.html",
controller:"ProductEditController as vm"
})
//product details
.state('ProductDetails',{
url:"/products/:productId",
templateUrl:"app/products/productDetailView.html",
Controller:"ProductDetailController as vm"
})
}]
);
}());
this is how my app.js looks like. I am having trouble on the last state, ProdcutDetails.
here is my ProductDetailController.
(function(){
"use strict";
angular
.module("ProductManagement")
.controller("ProductDetailController",
["ProductResource",$stateParams,ProductDetailsController]);
function ProductDetailsController(ProductResource,$stateParams)
{
var productId = $stateParams.productId;
var ref = $this;
ProductResource.get({productId: productId},function(data)
{
console.log(data);
});
}
}());
NOTE : I found lot of people have the same issue here https://github.com/angular-ui/ui-router/issues/136, I can't understand the solutions posted their because I am in a very beginning stage. Any explanation would be very helpful.
I created working plunker here
There is state configuration
$urlRouterProvider.otherwise('/home');
// States
$stateProvider
//home
.state("home",{
url:"/",
templateUrl:"app/welcome.html"
})
//products
.state("productList",{
url:"/products",
templateUrl:"app/products/productListView.html",
controller:"ProductController as vm"
})
//Edit product
.state('ProductEdit',{
url:"/products/edit/:productId",
templateUrl:"app/products/productEdit.html",
controller:"ProductEditController as vm"
})
//product details
.state('ProductDetails',{
url:"/products/:productId",
templateUrl:"app/products/productDetailView.html",
controller:"ProductDetailController as vm"
})
There is a definition of above used features
.factory('ProductResource', function() {return {} ;})
.controller('ProductController', ['$scope', function($scope){
$scope.Title = "Hello from list";
}])
.controller('ProductEditController', ['$scope', function($scope){
$scope.Title = "Hello from edit";
}])
.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
.controller('ProductDetailController', ProductDetailsController)
function ProductDetailsController ($scope, ProductResource, $stateParams)
{
$scope.Title = "Hello from detail";
var productId = $stateParams.productId;
//var ref = $this;
console.log(productId);
//ProductResource.get({productId: productId},function(data) { });
return this;
}
ProductDetailsController.$inject = ['$scope', 'ProductResource', '$stateParams'];
Check it here
But do you know what is the real issue? Just one line in fact, was the trouble maker. Check the original state def:
.state('ProductDetails',{
...
Controller:"ProductDetailController as vm"
})
And in fact, the only important change was
.state('ProductDetails',{
...
controller:"ProductDetailController as vm"
})
I.e. controller instead of Controller (capital C at the begining)
The params in controller definition array should be strings
["ProductResource", "$stateParams"...
This should properly help IoC to inject the $stateParams
And even better:
// the info for IoC
// the style which you will use with TypeScript === angular 2.0
ProductDetailsController.$inject = ["ProductResource", "$stateParams"];
// this will just map controller to its name, parmas are defined above
.controller("ProductDetailController", ProductDetailsController);

Angular - Return ID from URL Path in Controller

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;
}]);

Resources