How to pass multiple parameters to url using angular js? - javascript

I am a newbie to angular js .
Here in my project i want to pass multiple parameters in anchor tag .
So that i will get multiple params in address bar too.
I have tried this one but its not working at all.
Add New user
It is showing "http://localhost/Angular/#/edit-user/0",but i need to pass some more parameters.
Above is the code.
I want the url to be ""http://localhost/Angular/#/edit-user/0/add-user","
Here , am I doing anything wrong ?
Please suggest me .
Thank you.

You can do that like :
$state.go('editUser', {id: 0, pid: 0});
// or In your view :
<a ui-sref="editUser({id:0,pid:0})">Add New user</a>
In your config :
$stateProvider
.state('editUser', {
url: '/edit-user?id&pid',
views: {
'': {
templateUrl: 'users.html',
controller: 'MainCtrl'
},
},
params: {
id: null,
pid: null
}
})

Related

AngularJS UI-Router / $stateParams - Get data based on object ID

I have an app that directs to a custom url based on a given employeeId parameter when a particular employee is clicked on in a list. When the employee is clicked on, you are taken to an employee details page with their id property as a parameter, and I can display this property in the dom.
What I'm trying to do is to display this employee object's other properties in this different state, which I've had a look around at trying to do, but can't find a solution that matches what I'm trying to do.
Example:
Clicking on employee number 21101994 on employees/employeesList state directs to employees/employeeDetails/?21101994 page and displays only their data in the js fields such as {{employee.firstName}}.
I can successfully show the id, but I want to be able to show ALL of the data for the object that matches the employee's id.
The url routing is working fine, and clicking on this employee on the list page directs correctly to a details page with their parameter, but I can't seem to successfully pass their data into the new state/controller.
-
HTML link:
<li class="collection-item col-xs-12" data-ng-repeat="employee in employees | orderBy: sortByAllDepartments | filter:searchAllDepartments">
<a ui-sref="employees/employeeDetails({employeeId: employee.id})" class="employeeLink"></a>
-
What I've tried with the states:
.state('employees/employeesList', {
url: '/employees/employeesList',
templateUrl: 'pages/employees/employeesList.html',
controller: 'employeesListController'
})
.state('employees/employeeDetails', {
url: '/employees/employeeDetails/:employeeId',
templateUrl: 'pages/employees/employeeDetails.html',
resolve: {
employeeId: function($stateParams) {
return $stateParams.employeeId;
}
},
controller: function(employeeId) {
console.log(employeeId)
}
})
-
Employees service:
app.service('employeesService', function() {
var employees = [
{
id: '21101994',
firstName: 'Employee',
lastName: 'One'
}
];
var addEmployee = function(newObj) {
employees.push(newObj);
};
var getEmployees = function() {
return employees;
}
return {
addEmployee: addEmployee,
getEmployees: getEmployees
}
})
-
Employees List Controller:
app.controller('employeesListController', function($scope, $stateParams, employeesService) {
$scope.active = 'active';
$scope.sortByAllDepartments = '+lastName';
$scope.employees = employeesService.getEmployees();
})
The states will be receiving params like
url: '/employees/employeeDetails/{:employeeId}',
Or
url: '',
params: {
employeeId: null
},
resolve: {...}
I prefer the second one to receive due to clarity.
To pass all the data of employee, localstorage of employee object will be better in case you need this object frequently or in other parts in application.
localStorage.setItem('employeeData', JSON.stringify(empData));
To access this you can do
let empData = JSON.parse(localstorage.employeeData); //Object
In case you need to need this stored data, let's say you are navigating away from this employeeDetails state, you can delete this
localstorage.removeitem('employeeData');
If you require passing multiple state params, just add a comma separated string
ui-sref="employeeDetails({id: emp_id, name: emp_name, mobile: emp_mobile})"
and then receive this in state as below
params: {
employeeId: null,
employeeName: null,
employeeMobile: null
},
I hope this last makes clear as in why should you avoid passing too many params in stateParams

Get ancestor route params in Angular?

I have the following route hierarchy :
const appRoutes:Routes = [
{
path: 'article',
component: ArticleComponent,
children: [
{
path: '',
component: ArticleListComponent
},
{
path: ':articleId',
component: ArticleDetailComponent,
children: [
{
path: '',
component: PageListComponent
},
{
path: ':pageId',
component: PageComponent
}]
}]
},
{path: '**', component: DefaultComponent},
];
When I click the Article link , the page is navigated to :
"https://run.plnkr.co/article;listData=foo"
And then I see this :
Now , When I click at Article 2 , the page is navigated to
"https://run.plnkr.co/article;listData=foo/2;detailData=bar"
And then I see this :
Now , when I click at the Page 33 link , the page is navigated to :
"https://run.plnkr.co/article;listData=foo/2;detailData=bar/33;detailData=kro"
And then I see this:
OK
As you can see , at the innermost component ( the single page component) , I set some code to see the current params :
Page component! {{params | json}}
Which is populated in :
export class PageComponent {
constructor(private activatedRoute_:ActivatedRoute) {
activatedRoute_.params
.subscribe(params => {
this.params=params;
});
}
Question:
Currently the value of params value - is only { "pageId": "33", "detailData": "kro" } which belongs to the final route.
But how can I get the previous routes values ?
I know I can read the querystring but I find it an unconventional way .
The innermost url is :
"https://run.plnkr.co/article;listData=foo/2;detailData=bar/33;detailData=kro"
So basically I'm asking how can I extract all the parameters from prev routes.
( I mean what are the values for articleId , listData , detailsData (the first one) )?
PLNKR
You can get all parents params using snapshot. In detail component:
let node = activatedRoute_.snapshot;
while(node) {
console.log('component', node.component.name, ', params:', node.params);
node = node.parent;
}
component ArticleDetailComponent ,
params: Object {articleId: "1", detailData: "bar"}
component ArticleComponent , params: Object {listData: "foo"}
component RootComponent , params: Object {}
You should be sending the listData value along with the object.Modify this to your app/article-list.component.ts Component
<a [routerLink]="[articleId, {listData:'foo',detailData: 'bar'}]">
LIVE DEMO
You can manually send params when calling the states inside the links, but to be honest this is not the best solution.
My better suggestion is to use the resolve blocks of the states and implement resolvers in order to achieve that.
Every state will have the corresponding resolver which will resolve the params you need from the previous state.
Here the link to the documentation:
https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
The concept is that inside the resolve of the i state, you can still access the state parameters of the i-1 state, so you can pass them to the new state.

How can I maintain previous state param on 404?

I am new to working with Angular and I need some help with router-ui package.
Several of my states are made up of a dynamic value like so:
.state('state-name', {
url: `${dynamicValue}/state-name`,
abstract: true,
template: '<ui-view/>',
data: {
layout: {
footer: false
}
},
resolve: {
context: resolveContext
},
});
This value is passed via radio buttons that the user selects an option from. This all works fine, but the problem I am having is, if that user enters a wrong URL after choosing a value, it redirects them back to the first radio option rather than maintaining their choice. This is due to conditions I have setup if the user does not choose an option.
E.g.
Available Options:
1. 1234
2. 5678
If I choose:
5678
It generates this URL:
domain.com/5678/state-name
If I trigger a 404:
domain.com/5678/state-name/xyxyxyxyxxy
It redirects to:
domain.com/1234/state-name
Rather than:
domain.com/5678/state-name/
I have tried to modify the otherwise() function, but not having much luck. How can I maintain the previously chosen option, which is permanent until they choose a different option? Would it be better to modify the state within the controller $onInit() function?
Try this approach to resolve this issue.
.state('parentState', {
url: `:id/state-name`,
abstract: true,
template: '<ui-view/>',
data: {
layout: {
footer: false
}
},
resolve: {
context: resolveContext
},
}).state('childState', {
url: `:id/state-name/xyxyxy`,
abstract: true,
template: '<ui-view/>',
data: {
layout: {
footer: false
}
},
resolve: {
context: resolveContext
},
});
So, the first option will take 'id' parameter dynamically.
You can call it by passing id parameter to state name in ui-sref. Let say
<a ui-sref="childState({'id':5678})">
<input type="radio" value="5678" />
</a>
Same way you can create for others or call it using ng-repeat.
I hope it helps.

How to use AngularJS ui-router to build same URL as <ui-sref> in controller instead of HTML?

I'm using AngularJS's ui-router in my webapp. I have a state that looks like this:
$stateProvider.state('mystate',
{
url: '/mystate/{id:int}/:slug',
params: {
slug: {value: null, squash: true}
},
templateUrl: 'partials/mystate.html',
controller: 'MyStateCtrl'
}
);
I can link to this state in my view like this:
<a ui-sref="mystate({id: 4, slug: 'myslug'})">Hello World</a>
It converts it to the following URL: /mystate/4/myslug/
I want to build the same URL that ui-sref produces, but I want it inside MyStateCtrl. How do I do that? In the controller, I have access to $stateParams.id and $stateParams.slug. But what function do I need to call to convert them to that URL?
EDIT: Please note: I do not want to go to the resultant URL. I just want to have it for later use.
You can construct a url just like you ui-sref with the function $state.href(). You just need to provide the route and its params that you can get from $stateParams.
e.g. expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
So in your case:
$state.href("mystate", { id: $stateParams.id, slug: $stateParams.slug });
And here is the documentation - $state.href()
You can inject $state as a dependency to MyStateCtrl and use $state.go(to [, toParams] [, options]) function for navigating to target URL.
For example:
class MainController {
constructor($scope, $state) {
'ngInject';
this.scope = $scope;
this.state = $state;
}
navigateToAState() {
this.state.go('mystate',{id: 4, slug: 'myslug'})
}
}
export default MainController;
Detail Reference:
$state.go(to \[, toParams\] \[, options\])
A url generation method that returns the compiled url for the given state populated with the given params.
Example : expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
you can use this
$state.href ('mystate',{id: 4, slug: 'myslug'});
See This link for more help

How to make Automated Dynamic Breadcrumbs with AngularJS + Angular UI Router

One key component to web applications is breadcrumbs/navigation. With Angular UI Router, it would make sense to put the breadcrumb metadata with the individual states, rather than in your controllers. Manually creating the breadcrumbs object for each controller where it's needed is a straight-forward task, but it's also a very messy one.
I have seen some solutions for automated Breadcrumbs with Angular, but to be honest, they are rather primitive. Some states, like dialog boxes or side panels should not update the breadcrumbs, but with current addons to angular, there is no way to express that.
Another problem is that titles of breadcrumbs are not static. For example, if you go to a User Detail page, the breadcrumb title should probably be the user's Full Name, and not a generic "User Detail".
The last problem that needs to be solved is using all of the correct state parameter values for parent links. For example, if you're looking at a User detail page from a Company, obviously you'll want to know that the parent state requires a :companyId.
Are there any addons to angular that provide this level of breadcrumbs support? If not, what is the best way to go about it? I don't want to clutter up my controllers - I will have a lot of them - and I want to make it as automated and painless as possible.
Thanks!
I did solve this myself awhile back, because nothing was available. I decided to not use the data object, because we don't actually want our breadcrumb titles to be inherited by children. Sometimes there are modal dialogs and right panels that slide in that are technically "children views", but they shouldn't affect the breadcrumb. By using a breadcrumb object instead, we can avoid the automatic inheritance.
For the actual title property, I am using $interpolate. We can combine our breadcrumb data with the resolve scope without having to do resolves in a different place. In all of the cases I had, I just wanted to use the resolve scope anyway, so this works very well.
My solution also handles i18n too.
$stateProvider
.state('courses', {
url: '/courses',
template: Templates.viewsContainer(),
controller: function(Translation) {
Translation.load('courses');
},
breadcrumb: {
title: 'COURSES.TITLE'
}
})
.state('courses.list', {
url: "/list",
templateUrl: 'app/courses/courses.list.html',
resolve: {
coursesData: function(Model) {
return Model.getAll('/courses');
}
},
controller: 'CoursesController'
})
// this child is just a slide-out view to add/edit the selected course.
// It should not add to the breadcrumb - it's technically the same screen.
.state('courses.list.edit', {
url: "/:courseId/edit",
templateUrl: 'app/courses/courses.list.edit.html',
resolve: {
course: function(Model, $stateParams) {
return Model.getOne("/courses", $stateParams.courseId);
}
},
controller: 'CourseFormController'
})
// this is a brand new screen, so it should change the breadcrumb
.state('courses.detail', {
url: '/:courseId',
templateUrl: 'app/courses/courses.detail.html',
controller: 'CourseDetailController',
resolve: {
course: function(Model, $stateParams) {
return Model.getOne('/courses', $stateParams.courseId);
}
},
breadcrumb: {
title: '{{course.name}}'
}
})
// lots more screens.
I didn't want to tie the breadcrumbs to a directive, because I thought there might be multiple ways of showing the breadcrumb visually in my application. So, I put it into a service:
.factory("Breadcrumbs", function($state, $translate, $interpolate) {
var list = [], title;
function getProperty(object, path) {
function index(obj, i) {
return obj[i];
}
return path.split('.').reduce(index, object);
}
function addBreadcrumb(title, state) {
list.push({
title: title,
state: state
});
}
function generateBreadcrumbs(state) {
if(angular.isDefined(state.parent)) {
generateBreadcrumbs(state.parent);
}
if(angular.isDefined(state.breadcrumb)) {
if(angular.isDefined(state.breadcrumb.title)) {
addBreadcrumb($interpolate(state.breadcrumb.title)(state.locals.globals), state.name);
}
}
}
function appendTitle(translation, index) {
var title = translation;
if(index < list.length - 1) {
title += ' > ';
}
return title;
}
function generateTitle() {
title = '';
angular.forEach(list, function(breadcrumb, index) {
$translate(breadcrumb.title).then(
function(translation) {
title += appendTitle(translation, index);
}, function(translation) {
title += appendTitle(translation, index);
}
);
});
}
return {
generate: function() {
list = [];
generateBreadcrumbs($state.$current);
generateTitle();
},
title: function() {
return title;
},
list: function() {
return list;
}
};
})
The actual breadcrumb directive then becomes very simple:
.directive("breadcrumbs", function() {
return {
restrict: 'E',
replace: true,
priority: 100,
templateUrl: 'common/directives/breadcrumbs/breadcrumbs.html'
};
});
And the template:
<h2 translate-cloak>
<ul class="breadcrumbs">
<li ng-repeat="breadcrumb in Breadcrumbs.list()">
<a ng-if="breadcrumb.state && !$last" ui-sref="{{breadcrumb.state}}">{{breadcrumb.title | translate}}</a>
<span class="active" ng-show="$last">{{breadcrumb.title | translate}}</span>
<span ng-hide="$last" class="divider"></span>
</li>
</ul>
</h2>
From the screenshot here, you can see it works perfectly in both the navigation:
As well as the html <title> tag:
PS to Angular UI Team: Please add something like this out of the box!
I'd like to share my solution to this. It has the advantage of not requiring anything to be injected into your controllers, and supports named breadcrumb labels, as well as using resolve: functions to name your breadcrumbs.
Example state config:
$stateProvider
.state('home', {
url: '/',
...
data: {
displayName: 'Home'
}
})
.state('home.usersList', {
url: 'users/',
...
data: {
displayName: 'Users'
}
})
.state('home.userList.detail', {
url: ':id',
...
data: {
displayName: '{{ user.name | uppercase }}'
}
resolve: {
user : function($stateParams, userService) {
return userService.getUser($stateParams.id);
}
}
})
Then you need to specify the location of the breadcrumb label (displayname) in an attribute on the directive:
<ui-breadcrumbs displayname-property="data.displayName"></ui-breadcrumbs>
In this way, the directive will know to look at the value of $state.$current.data.displayName to find the text to use.
$interpolate-able breadcrumb names
Notice that in the last state (home.userList.detail), the displayName uses the usual Angular interpolation syntax {{ value }}. This allows you to reference any values defined in the resolve object in the state config. Typically this would be used to get data from the server, as in the example above of the user name. Note that, since this is just a regular Angular string, you can include any type of valid Angular expression in the displayName field - as in the above example where we are applying a filter to it.
Demo
Here is a working demo on Plunker: http://plnkr.co/edit/bBgdxgB91Z6323HLWCzF?p=preview
Code
I thought it was a bit much to put all the code here, so here it is on GitHub: https://github.com/michaelbromley/angularUtils/tree/master/src/directives/uiBreadcrumbs
I made a Angular module which generate a breadcrumb based on ui-router's states. All the features you speak about are included (I recently add the possibility to ignore a state in the breadcrumb while reading this post :-) ) :
Here is the github repo
It allows dynamic labels interpolated against the controller scope (the "deepest" in case of nested/multiple views).
The chain of states is customizable by state options (See API reference)
The module comes with pre-defined templates and allows user-defined templates.
I do not believe there is built in functionality, but all the tools are there for you, take a look at the LocationProvider. You could simply have navigation elements use this and whatever else you want to know just inject it.
Documentation
After digging deep into the internals of ui-router I understood how I could create a breadcrumb using resolved resources.
Here is a plunker to my directive.
NOTE: I couldn't get this code to work properly within the plunker, but the directive works in my project. routes.js is provided merely for example of how to you can set titles for your breadcrumbs.
Thanks for the solution provided by #egervari. For those who need add some $stateParams properties into custom data of breadcrumbs. I've extended the syntax {:id} for the value of key 'title'.
.state('courses.detail', {
url: '/:courseId',
templateUrl: 'app/courses/courses.detail.html',
controller: 'CourseDetailController',
resolve: {
course: function(Model, $stateParams) {
return Model.getOne('/courses', $stateParams.courseId);
}
},
breadcrumb: {
title: 'course {:courseId}'
}
})
Here is an Plunker example. FYI.

Categories

Resources