AngularJS Inserting child state parameter into $urlRouterProvider (UI-Router) - javascript

I'm trying to use $urlRouterProvider to redirect me from a parent state to a child one, though the child one is a URL that accepts a parameter. (child url: /:page?pageId).
I am simply hoping to enter the application by entering from www.example.com/home, where the $urlRouterProvider should then take over the routing.
The code looks something like this:
$urlRouterProvider.when('/home', '/home/?pageId=1');
$stateProvider.state('home', {
url: '/home',
abstract: true,
templateUrl: 'home.tpl.html'
}).state('home.page', {
url: '/:page?pageId',
templateUrl: '...'
});
As you can see, I was hoping that by using the $urlRouterProvider I would be able to direct the location from the /home (parent state) to the parameterized child state /:page?pageId by forcing the url /?pageId=1. Instead, it just appends a trailing slash to /home/.
Here is a very dysfunctional plnkr of this madness: http://plnkr.co/edit/XZ4jkhqzQmykIgx0CvH2?p=preview
Thanks!

There is a working plunker
I am not sure why the above notation is not working (if intended to skip it or not), but with this adjustment it will work:
$stateProvider.state('home', {
url: '/home',
abstract: true,
templateUrl: 'home.html',
controller: 'controller',
}).state('home.child', {
url: '/:page?pageId',
templateUrl: 'childtemplate.html',
params : { // HERE we do define the defaults
pageId: {value: 1}, // these would serve as a starting value
}
});
So, what we are effectively doing here, is to declaring the default value out of url, but in the params: {} setting:
...
params : {
pageId: {value: 1},
}
Check it here

Related

Click on one div and make Angular template open in another

I want to be able to click on the anchor in the #leftDiv and make the UI router template open in the #rightDiv. So, when I click on Hello Plunker 1 in the #leftDiv, I want peopleOne.html to open in the #rightDiv. When I click on Hello Plunker 2, I want peopleTwo.html to replace peopleOne.html in the #rightDiv.
Here is a Plunker - https://plnkr.co/edit/T8RTgea8VccA9mdBABGC?p=preview
Can someone provide insight into why this is not working.
Script.js
var Delivery = angular.module('Delivery', ['ui.router']);
angular
.module('Delivery')
.config(function($stateProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$stateProvider
.state('home', {
url: '/Delivery',
views: {
'view': {
templateUrl: 'Delivery.html',
},
},
})
.state('peopleOne', {
url: '/peopleOne',
parent: 'home',
views: {
'view#': {
templateUrl: 'peopleOne.html'
}
},
})
.state('peopleTwo', {
url: '/peopleTwo',
parent: 'home',
views: {
'view#': {
templateUrl: 'peopleTwo.html'
}
},
})
})
A few problems I've noticed:
First, put a console.log after the $stateProvider configuration calls to setup your routes. You will see that this code is never even called. Your angular app is not quite set up properly. You are using dat-ng-app in the index template, when you should be using ng-app. Otherwise angular is never actually used.
The next issue is in your $stateProvider configuration. I am not sure which documentation you are following, but your configurations for the states should look something like this:
# Set the default state
$urlRouterProvider.otherwise('/home')
# Configures home, peopleOne, and peopleTwo states
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html'
})
.state('peopleOne', {
url: '/peopleOne',
templateUrl: 'peopleOne.html',
parent: 'home'
})
.state('peopleTwo', {
url: '/peopleTwo',
templateUrl: 'peopleTwo.html',
parent: 'home'
})
Finally, when actually creating the links in your template, I find it easier to use the ui-sref tag, which allows you to create a link based on a state name. So a link to the peopleOne state would look like this: <a ui-sref="peopleOne"></a>.
I've attached a plunker based off your original code
https://plnkr.co/edit/NazuoFoDOa3VGR6smoyH

Problems navigating to Angular UI router state

I have a route definition as follows:
$stateProvider
.state('vehicles', {
url: '/vehicles',
templateUrl: 'foo/bar1.html'
}).state('vehicles.id', {
url: '/{id}',
templateUrl: 'foo/bar3.html'
}).state('vehicles.create', {
url: '/create',
templateUrl: 'foo/bar2.html',
controller: 'VehicleCreateController'
});
I have a button that does
$state.go("vehicles.create");
The problem is, that while the URL changes correctly, the page remains the same. Only after the second click, the correct template appears.
After a hint from my colleague I realized, that it was the state definitions that caused the problem. Reordering the states from "more specific" (URL-wise - i.e. /create) to less specific (/{id}) did the trick. So the thing that was wrong was having the more generic URL /vehicles/{id} before the very similar, but less generic /vehicles/create.
So here's the improved version:
$stateProvider
.state('vehicles', {
url: '/vehicles',
templateUrl: 'foo/bar1.html'
}).state('vehicles.create', {
url: '/create',
templateUrl: 'foo/bar2.html',
controller: 'VehicleCreateController'
}).state('vehicles.id', {
url: '/{id}',
templateUrl: 'foo/bar3.html'
});
use : for your params and ? to make those params optional if you need.
check the below code snippet, for routing with params.
$stateProvider
.state('contacts.detail', {
url: "/contacts/:contactId",
templateUrl: 'contacts.detail.html',
controller: function ($stateParams) {
// If we got here from a url of /contacts/42
expect($stateParams).toBe({contactId: "42"});
}
})
check this for more clear view on routing.

Angular UI-router, nested states don't show

I have a UI-Router document set up to show the "pages" sections of a demo.
(function() {
'use strict';
angular.module('pb.ds.pages').config(function($stateProvider) {
$stateProvider.state('pages', {
abstract: true,
url: '/pages',
templateUrl: 'modules/pages/templates/pages.html',
controller: 'PagesController as pages',
data: {
pageTitle: 'Pages',
access: 'public',
bodyClass: 'pages'
}
})
.state('pages.signin', {
url: '/signin',
templateURL: 'modules/pages/templates/signin.html',
controller: 'SignInController as signin'
})
.state('pages.forgotpassword', {
url: '/forgotpassword',
templateURL: 'modules/pages/templates/forgotpassword.html',
controller: 'ForgotPasswordController as forgot'
})
.state('pages.404', {
url: '/404',
templateURL: 'modules/pages/templates/404.html',
controller: '404Controller'
});
});
})();
The parent state, "pages" has the ui-view on it, but otherwise I don't need to "show" it. I am only interested in showing its children, such as pages.signin or pages.forgotpassword.
Typing in the url "/forgotpassword" bounces me back to my homepage, which is the "otherwise" state in my app.module.js
// UI ROUTER CONFIG
angular.module('app').config(function($stateProvider) {
$stateProvider.state('otherwise', {
url: '*path',
template: '',
controller: function($state) {
$state.go('dashboard');
}
});
});
No errors in console, and all the pages in question are linked in my index.html.
I'm sure I must have missed something obvious. Any clues?
UPDATE
If I enter /pages/forgotpassword it does go to the correct path but the view is not being populated by the template...
There is a working plunker
We have to adjust state definition like this:
$stateProvider.state('pages', {
abstract: true,
//url: '/pages',
templateUrl: 'modules/pages/templates/pages.html',
controller: 'PagesController as pages',
data: {
pageTitle: 'Pages',
access: 'public',
bodyClass: 'pages'
}
})
.state('pages.signin', {
url: '/signin',
// templateURL: 'modules/pages/templates/signin.html',
templateUrl: 'modules/pages/templates/signin.html',
controller: 'SignInController as signin'
})
.state('pages.forgotpassword', {
url: '/forgotpassword',
//templateURL: 'modules/pages/templates/forgotpassword.html',
templateUrl: 'modules/pages/templates/forgotpassword.html',
controller: 'ForgotPasswordController as forgot'
})
The most important is replacement of the templateURL with templateUrl. Javascript (and UI-Router) is case sensitive.
We also do not need define url for parent... it could be just child state definition
Finally, we must be sure, that our parent contains some target ui-view="" where child states will be placed. E.g. this is the plunker pages.html:
<div>
<h3>pages</h3>
<hr />
<div ui-view=""></div>
</div>
These links will then work as expected:
//href
<a href="#/signin">
<a href="#/forgotpassword">
//ui-sref
<a ui-sref="pages.signin">
<a ui-sref="pages.forgotpassword">
We can leave the parent url:
$stateProvider.state('pages', {
abstract: true,
url: '/pages',
...
but the href links for child states must contain the parent url as well:
<a href="#/pages/signin">
<a href="#/pages/forgotpassword">
Check it here in action
You need to prefix the state url with the url of the parent state. So the correct url that you need open with the browser should be: #/pages/forgotpassword
Check the doc URL Routing for Nested States

Angular JS - UI router page reload won't set the state

This is my main app (app.js)
(function(ng, module) {
module.config(['$stateProvider', '$urlRouterProvider', function( $stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("app");
$stateProvider.state('login', {
url: 'login',
templateUrl: '/assets/templates/pages/login.html'
}).state('root', {
url: '',
templateUrl: '/assets/templates/pages/index.html'
});
}]);
}) (angular, angular.module('myapp', ['ui.router', 'myapp.submodule']));
This is the submodule (submodule.js)
(function(ng, module) {
module.config(['$stateProvider', function($stateProvider){
$stateProvider.state('root.substate', {
url: 'todo/{type}',
templateUrl: '/assets/app/todo/todo.html',
controller: function($stateParams, $scope) {
// Do stuff.
}
});
}]);
}) (angular, angular.module('myapp.submodule', ['ui.router']));
The expected behaviour would be
redirect to "app" url when no matching route is found
activate the "root" state on root url
activate the "root.substate" state on /todo url
This is working fine.
However, if i do refresh the page, the state is not activated and i'm sent back to "app". Why?
We have two root states (no parent) states. These should be either having no url, or it should start with some unique sign - the best choice would always with (URI spec) be a /:
// domain/app/login - easy to find
.state('login', {
url: 'login',
...
})
// no def === domain/app
.state('root', {
url: '',
...
});
Now, let's use some url even for our 'root' state :
// domain/app/
.state('root', {
url: '/',
...
});
That mans, that our child 'root.substate' will also contain the parent url part. So if we would use this
// this is a child and its url will be in fact: domain/app//todo/sometype
.state('root.substate', {
url: '/todo/{type}',
...
});
See, that this way, our url will now for child contain // (double slash)
To avoid that, we can use UI-Router feature '^'
// this stat will not use the parent part
// this will work domain/app/todo/sometype
.state('root.substate', {
url: '^/todo/{type}',
...
});
Check the doc:
Absolute Routes (^)
If you want to have absolute url matching, then you need to prefix your url string with a special symbol '^'.
$stateProvider
.state('contacts', {
url: '/contacts',
...
})
.state('contacts.list', {
url: '^/list',
...
});
I know a lot of time left. But about issue with refreshing. If you want to stay on the same url address as before refreshing you should add next:
angular.module('app').run(['$state', '$stateParams', function($state, $stateParams) {
//this solves page refresh and getting back to state
}]);
like mentioned here in pre-last answer

Angular UI-Router passing data between states with go function does not work

I just started learning angularjs and I am using angular-ui-router. I am trying to send data from one state to another using $state.go but I have no success. Here is what I have so far:
I have not included the html intentionally because I assumed it was not needed if it is needed please tell me and I will add it.
I have configured my states as below:
$stateProvider
.state('public', {
abstract: true,
templateUrl: 'App/scripts/main/views/PublicContentParent.html'
})
.state('public.login', {
url: '/login',
templateUrl: 'App/scripts/login/views/login.html',
controller: 'loginCtrl'
})
$stateProvider
.state('private', {
abstract: true,
templateUrl: 'App/scripts/main/views/PrivateContentParent.html'
})
.state('private.visits', {
url: '/visits',
views: {
'main': {
controller: 'visitsListCtrl',
templateUrl: 'App/scripts/visits/views/VisitsList.html'
}
}
});
When my LoginController is invoked it will execute the below code:
loginModule.controller('loginCtrl', ['$state', function ($scope, $state) {
$state.go('private.visits', { name : "Object"});
}]);
When the private.visits page is active, I am trying to print the $stateParams:
visitsModule.controller('visitsListCtrl', ['$stateParams',
function ($stateParams) {
console.log($stateParams);
}]);
As things state $stateParams is an empty object. I expected it to to contain the object I passed in loginCtrl.
EDIT
It seems that if private.visits url has this url format '/visits/:name' and I also add the property params: ["name"] I get access to the object I send from the public.login state.
The side effect is that the parameters are added to the url which is logical.
I tried doing the same thing with a child state with no url, and in this case it seems that I do not have access to the params I passed from public.login.
How do I send data in child states?
What you have to do is to define the name param in the private.visits state like:
$stateProvider
.state('public', {
abstract: true,
templateUrl: 'App/scripts/main/views/PublicContentParent.html'
})
.state('public.login', {
url: '/login',
templateUrl: 'App/scripts/login/views/login.html',
controller: 'loginCtrl'
})
$stateProvider
.state('private', {
abstract: true,
templateUrl: 'App/scripts/main/views/PrivateContentParent.html'
})
.state('private.visits', {
// NOTE!
// Previously, we were only passing params as an array
// now we are sending it as an object. If you
// send this as an array it will throw an error
// stating id.match is not a function, so we updated
// this code. For further explanation please visit this
// url http://stackoverflow.com/a/26204095/1132354
params: {'name': null},
url: '/visits',
views: {
'main': {
controller: 'visitsListCtrl',
templateUrl: 'App/scripts/visits/views/VisitsList.html',
resolve: {
name: ['$stateParams', function($stateParams) {
return $stateParams.name;
}]
}
}
}
});
And then in the controller access to the name:
visitsModule.controller('visitsListCtrl', ['name',
function (name) {
console.log(name);
}]);
Hope it help you!
When you say:
$state.go('private.visits', { name : "Object"});
You're not passing data to the private.visits state, but rather you're setting a parameter to the private.visits state, which doesn't even support parameters as you have not defined parameters for it in the state config. If you want to share data between states use a service, or if your states have a parent-child relationship then the child state will have access to the parent states data. Seeing as how you don't want the data to sow up in your URLs, I would use a service (getters/setters) to achieve this.

Categories