Exposing the current state name with ui router - javascript

I'm trying to implement a language switcher where if a user clicks on "de" from any given page on an "en" side - it takes them to that page of the "de" side. If I console.dir the $state parameter, it exposes the values I'd want with the "current" property of the given $state. If I try to console.dir the $state.current to focus on the values I want, it only gives the parent state property (my current views are nested).
My current thinking is, I'm on url/en/content, and dynamically I can then have my lang navigation dynamically load the appropriate destination points into some kind of data attribute, pick those up with a custom directive where I'd initiate a "go to" and set my preferedLanguage value per angular-translate.
The key issue at the moment is exposing that $state name - again, when simply browsing $state the current object gives the values I'd want, but $current.state directly only gives the parent state.
If anyone has a better suggestion of how to do this (in a angular way - no custom cookie junk) I'm happy to take suggestions.
Thanks!
Update! CODE SAMPLES:
Object reference of my states:
var urlStates = {
en: {
home: {
name: 'home',
url: '/en',
templateUrl: 'templates/'+lang+'/home.html',
abstract: 'true'
},
home_highlights: {
name:'home.highlights',
url: '',
templateUrl: 'templates/'+lang+'/home.highlights.html'
},
home_social:
{
name: 'home.social',
url: '/social',
templateUrl: 'templates/'+lang+'/home.social.html'
},
home_map:
{
name: 'home.map',
url: '/map',
templateUrl: 'templates/'+lang+'/home.map.html'
}
};
My States:
$stateProvider
.state(urlStates.en.home)
.state(urlStates.en.home_highlights)
.state(urlStates.en.home_social)
.state(urlStates.en.home_map);
$locationProvider.html5Mode(true);
})
Controller:
.controller('LandingPage', function($translate, $state){
this.state = $state;
this.greeting = "Hello";
});
And Lastly, the output I see in the dom:
With this.state = $state;
{
"params": {},
"current": {
"name": "home.highlights",
"url": "",
"templateUrl": "templates/en/home.highlights.html" },
"transition": null
}
With this.state = $state.current
{
"name": "",
"url": "^",
"views": null,
"abstract": true
}

this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
http://plnkr.co/edit/LGMZnj?p=preview

Answering your question in this format is quite challenging.
On the other hand you ask about navigation and then about current $state acting all weird.
For the first I'd say it's too broad question and for the second I'd say... well, you are doing something wrong or missing the obvious :)
Take the following controller:
app.controller('MainCtrl', function($scope, $state) {
$scope.state = $state;
});
Where app is configured as:
app.config(function($stateProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.state('main.thiscontent', {
url: '/thiscontent',
templateUrl: 'this.html',
controller: 'ThisCtrl'
})
.state('main.thatcontent', {
url: '/thatcontent',
templateUrl: 'that.html'
});
});
Then simple HTML template having
<div>
{{ state | json }}
</div>
Would "print out" e.g. the following
{
"params": {},
"current": {
"url": "/thatcontent",
"templateUrl": "that.html",
"name": "main.thatcontent"
},
"transition": null
}
I put up a small example showing this, using ui.router and pascalprecht.translate for the menus. I hope you find it useful and figure out what is it you are doing wrong.
Plunker here http://plnkr.co/edit/XIW4ZE
Screencap

In my current project the solution looks like this:
I created an abstract Language State
$stateProvider.state('language', {
abstract: true,
url: '/:language',
template: '<div ui-view class="lang-{{language}}"></div>'
});
Every state in the project has to depend on this state
$stateProvider.state('language.dashboard', {
url: '/dashboard'
//....
});
The language switch buttons calls a custom function:
<a ng-click="footer.setLanguage('de')">de</a>
And the corresponding function looks like this (inside a controller of course):
this.setLanguage = function(lang) {
FooterLog.log('switch to language', lang);
$state.go($state.current, { language: lang }, {
location: true,
reload: true,
inherit: true
}).then(function() {
FooterLog.log('transition successfull');
});
};
This works, but there is a nicer solution just changing a value in the state params from html:
<a ui-sref="{ language: 'de' }">de</a>
Unfortunately this does not work, see https://github.com/angular-ui/ui-router/issues/1031

Use Timeout
$timeout(function () { console.log($state.current, 'this is working fine'); }, 100);
See - https://github.com/angular-ui/ui-router/issues/1627

I wrapped around $state around $timeout and it worked for me.
For example,
(function() {
'use strict';
angular
.module('app')
.controller('BodyController', BodyController);
BodyController.$inject = ['$state', '$timeout'];
/* #ngInject */
function BodyController($state, $timeout) {
$timeout(function(){
console.log($state.current);
});
}
})();

Its just because of the load time angular takes to give you the current state.
If you try to get the current state by using $timeout function then it will give you correct result in $state.current.name
$timeout(function(){
$rootScope.currState = $state.current.name;
})

Related

angularjs - ui.router not rendering ui-view immediately

I am trying to use ui-router on my project.
Core module:
var core = angular.module('muhamo.core', ['angular-loading-bar', 'anguFixedHeaderTable', 'ui.router']);
Tracking module:
var app = angular.module(TRACKING_MODULE_NAME, ['muhamo.core']);
app.config(Configure);
Configure.$inject = ['$stateProvider', '$urlRouterProvider'];
function Configure($stateProvider, $urlRouterProvider) {
$stateProvider.state('contacts', {
templateUrl: '/static/partials/employee/employee-edit',
controller: function () {
this.title = 'My Contacts';
},
controllerAs: 'contact'
});
$urlRouterProvider.otherwise("/contacts");
console.log($stateProvider);
}
and the html definition :
<div ui-view></div>
It works fine if i click to a ui-sref link. But on page load it does not load the default view "/contacts". Am I missing something here?
UPDATE
It works after adding missing "url" property. But now I've another problem, if I extend my implementation like that :
function Configure($stateProvider, $urlRouterProvider) {
$stateProvider.state('employees', {
abstract: true,
url: "/employees"
/* Various other settings common to both child states */
}).state('employees.list', {
url: "", // Note the empty URL
templateUrl: '/static/partials/employee/employee-list'
});
$urlRouterProvider.otherwise("/employees");
console.log($stateProvider);
}
also with more states, ui-view is not rendering.
There are two fishy things in your implementation. You out an empty url and your default route is abstract. Try my changes below.
function Configure($stateProvider, $urlRouterProvider) {
$stateProvider.state('employees', {
abstract: true,
url: "/employees"
/* Various other settings common to both child states */
}).state('employees.list', {
url: "/list", // Note the empty URL
templateUrl: '/static/partials/employee/employee-list'
});
$urlRouterProvider.otherwise("/employees/list");
console.log($stateProvider);
Cheers
Yes. You need to set the state.url to '/contacts'
$stateProvider.state('contacts', {
url: '/contacts',
templateUrl: '/static/partials/employee/employee-edit',
controller: function () {
this.title = 'My Contacts';
},
controllerAs: 'contact'
});
It seems you forgot to set the url parameter, e.g.:
$stateProvider.state('contacts', {
url: "/contacts",
...
}

AngularJS UI Router data persists when navigating from grand-child to parent

I am having weird issue probably caching issue while navigating from grand-child(/dashboard/1/production) to parent(/dashboard).
Following are few screenshots:
The selections i.e Delphi-UI and production shouldn't persists.
Following is my snippet of application config:
$stateProvider
.state('root', {
url: '/',
views: {
'header': {
templateUrl: 'ngapp/templates/header.html'
}
}
})
// dashboard routes
.state('root.dashboard', {
url: 'dashboard',
views: {
'content#' : {
templateUrl: 'ngapp/home/templates/dashboard.html',
controller: 'DashboardCtrl',
controllerAs: 'vm'
}
}
})
.state('root.dashboard.app', {
url: '/{id:int}',
views: {
'body#root.dashboard' : {
templateUrl: 'ngapp/home/templates/dashboard-body.html',
controller: 'DashboardBodyCtrl'
}
}
})
.state('root.dashboard.app.env', {
url: '/:name',
views: {
'body#root.dashboard' : {
templateUrl: 'ngapp/home/templates/env-content.html',
controller: 'EnvContentCtrl'
}
}
});
And DashboardCtrl is:
controllers.controller('DashboardCtrl', ['$scope', '$http', '$state', '$timeout', 'appsFactory', function($scope, $http, $state, $timeout, appsFactory) {
$scope.envs = [];
$scope.deps = [];
$scope.envBtnText = $scope.appBtnText = "Choose here";
$scope.headerTitle = "Environment Configuration And Management";
$scope.appStatus = {
isopen: false
};
$scope.envStatus = {
isopen: false
};
appsFactory.list(function(data) {
$scope.apps = data;
});
}]);
Full controller code : http://goo.gl/BWtiU5
Project hosted here : https://github.com/budhrg/atlantis-dashboard
Also, navigating back to Atlantis UI(dashboard) doesn't reset data like
$scope.envs, $scope.deps, $scope.envBtnText and $scope.appBtnText.
What might be issue here? Am I missing anything?
Nested States & Views
When the application is in a particular state—when a state is "active"—all of its ancestor states are implicitly active as well. Below, when the "contacts.list" state is active, the "contacts" state is implicitly active as well, because it's the parent state to "contacts.list".
Your controller isn't getting re-instantiated (expected). There are a couple ways to handle this.
See:
How to make angular ui-router's parent state always execute controller code when state changes?

Pass sub-state from sub-module to the main module in angular.js with angular-ui-router

I design my SPA like this:
angular.module('app', ['submodule0', 'submodule1']);
Main module:
$stateProvider.state("sub0index", {
url: "/sub0",
// pass states defined in submodule0, is that possible?
}).state("sub1index", {
url: "/sub1",
// pass states defined in submodule1
})
And here are some states defined in submodule0
$stateProvider.state("index", {
url: "/index",
templateUrl: "template/index.html"
}).state("info", {
url: "/info",
templateUrl: "template/info.html"
})
So is that possible that I pass sub-state from sub-module to the main module? I ask this because now I define all my state in my main module, I think it may be more elegant to define the state of one submodule in the submodule itself.
And another question is: I'm not sure my module design is reasonable or not, is my submodules not necessary? Or just keep my whole app logic to one module? Thanks.
====Edited====
And here is the problem I've met.
var app = angular.module('test', ['ui.router', 'app.sub']);
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('index', {
url: "/a",
views: {
"general": {
templateUrl: "/template.html"
}
},
resolve: {
data: 'GetDataService'
}
});
}
The service GetDataService is defined in my submodule app.sub, and here is the service:
angular.module('app.sub',['ui.router'])
.service('GetDataService', ['$stateParams', function($stateParams) {
console.log($stateParams);
return null; // return null just for demo
}]);
The output of console.log($stateParams) is an empty object. But if use the service which is defined in its own module, the current state can be get correctly. So whats the issue?
===Edit===
Thanks for the example, it works fine if give a factory to data directly. But how about I give it a string?
I check the document of ui-router, and there is something about map object in resolve:
factory - {string|function}: If string then it is alias for service.
So if I use the code like this:
resolve: {
data: "GetDataService"
}
And the definition of GetDataService:
.service('GetDataService', ['$stateParams', function($stateParams) {
console.log($stateParams);
return null;
}])
But output of console.log($stateParams) is always an empty object.
Do I have some misunderstanding about the api document?
===Edit again===
If I use code like this:
resolve: {
// data: "GetDataService"
data: ['$stateParams', function($stateParams) {
console.log($stateParams);
return null;
}]
}
I can get the params object.
I would say, that modules should not stop us... we can split the app into many if needed.
But I would suggest: Services should be independent on $state.current. We should pass to them function parameters as needed, but these should be resolved outside of the Service body.
Bette would be to show it in action - there is one working example
This is the service:
angular.module('app.sub',['ui.router'])
.service('DataService', ['$state', function($state) {
return {
get: function(stateName, params){
console.log(stateName);
console.log(params);
return stateName;
}
}
}]);
And here is some adjsuted state def:
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('index', {
url: "/a/{param1}",
views: {
"general": {
templateUrl: "tpl.html"
}
},
resolve: {
data: ['DataService','$stateParams'
, function(DataService,$stateParams, $state){
return DataService.get('index', $stateParams)
}],
},
});
}])
Hope it helps a bit. The plunker link
Because this approach is ready to test service without any dependency on some "external" $state.current. We can just pass dummy, testing params

AngularJS ui-router: how to resolve typical data globally for all routes?

I have an AngularJS service which communicates with the server and returns
translations of different sections of the application:
angular
.module('utils')
.service('Translations', ['$q','$http',function($q, $http) {
translationsService = {
get: function(section) {
if (!promise) {
var q = $q.defer();
promise = $http
.get(
'/api/translations',
{
section: section
})
.success(function(data,status,headers,config) {
q.resolve(result.data);
})
.error(function(data,status,headers,config){
q.reject(status);
});
return q.promise;
}
}
};
return translationsService;
}]);
The name of the section is passed as the section parameter of the get function.
I'm using AngularJS ui-router module and following design pattern described here
So I have the following states config:
angular.module('app')
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('users', {
url: '/users',
resolve: {
translations: ['Translations',
function(Translations) {
return Translations.get('users');
}
]
},
templateUrl: '/app/users/list.html',
controller: 'usersController',
controllerAs: 'vm'
})
.state('shifts', {
url: '/shifts',
resolve: {
translations: ['Translations',
function(Translations) {
return Translations.get('shifts');
}
]
},
templateUrl: '/app/shifts/list.html',
controller: 'shiftsController',
controllerAs: 'vm'
})
This works fine but as you may notice I have to explicitly specify translations in the resolve parameter. I think that's not good enough as this duplicates the logic.
Is there any way to resolve translations globally and avoid the code duplicates. I mean some kind of middleware.
I was thinking about listening for the $stateChangeStart, then get translations specific to the new state and bind them to controllers, but I have not found the way to do it.
Any advice will be appreciated greatly.
Important note:
In my case the resolved translations object must contain the translations data, not service/factory/whatever.
Kind regards.
Let me show you my approach. There is a working plunker
Let's have a translation.json like this:
{
"home" : "trans for home",
"parent" : "trans for parent",
"parent.child" : "trans for child"
}
Now, let's introduce the super parent state root
$stateProvider
.state('root', {
abstract: true,
template: '<div ui-view=""></div>',
resolve: ['Translations'
, function(Translations){return Translations.loadAll();}]
});
This super root state is not having any url (not effecting any child url). Now, we will silently inject that into every state:
$stateProvider
.state('home', {
parent: 'root',
url: "/home",
templateUrl: 'tpl.html',
})
.state('parent', {
parent: 'root',
url: "/parent",
templateUrl: 'tpl.html',
})
As we can see, we use setting parent - and do not effect/extend the original state name.
The root state is loading the translations at one shot via new method loadAll():
.service('Translations', ['$http'
,function($http) {
translationsService = {
data : {},
loadAll : function(){
return $http
.get("translations.json")
.then(function(response){
this.data = response.data;
return this.data;
})
},
get: function(section) {
return data[section];
}
};
return translationsService;
}])
We do not need $q at all. Our super root state just resolves that once... via $http and loadAll() method. All these are now loaded, and we can even place that service into $rootScope:
.run(['$rootScope', '$state', '$stateParams', 'Translations',
function ($rootScope, $state, $stateParams, Translations) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.Translations = Translations;
}])
And we can access it anyhwere like this:
<h5>Translation</h5>
<pre>{{Translations.get($state.current.name) | json}}</pre>
Wow... that is solution profiting almost from each feature coming with UI-Router... I'd say. All loaded once. All inherited because of $rootScope and view inheritance... all available in any child state...
Check that all here.
Though this is a very old question, I'd like to post solution which I'm using now. Hope it will help somebody in the future.
After using some different approaches I came up with a beautiful angularjs pattern by John Papa
He suggest using a special service routerHelperProvider and configure states as a regular JS object. I'm not going to copy-paste the entire provider here. See the link above for details. But I'm going to show how I solved my problem by the means of that service.
Here is the part of code of that provider which takes the JS object and transforms it to the states configuration:
function configureStates(states, otherwisePath) {
states.forEach(function(state) {
$stateProvider.state(state.state, state.config);
});
I transformed it as follows:
function configureStates(states, otherwisePath) {
states.forEach(function(state) {
var resolveAlways = {
translations: ['Translations', function(Translations) {
if (state.translationCategory) {
return Translations.get(state.translationCategory);
} else {
return {};
}
}],
};
state.config.resolve =
angular.extend(state.config.resolve || {}, resolveAlways || {});
$stateProvider.state(state.state, state.config);
});
});
And my route configuration object now looks as follows:
{
state: ‘users’,
translationsCategory: ‘users’,
config: {
controller: ‘usersController’
controllerAs: ‘vm’,
url: ‘/users’.
templateUrl: ‘users.html'
}
So what I did:
I implemented the resolveAlways object which takes the custom translationsCategory property, injects the Translations service and resolves the necessary data. Now no need to do it everytime.

Angular ui-router variable in nested view

I'm currently working on an app where I have multiple nested views, they sort of look like this:
- ui-view
- ui-view="header"
- ui-view="nav"
- ui-view="body"
My states are defined as follows:
.state('index', {
url: '', // default route
templateUrl: 'welcome.html'
})
.state('app', {
abstract: true,
templateUrl: 'app.template.html' // This template contains the 3 different ui-views
})
// I'm using a different state here so I can set the navigation and header by default
.state('in-app', {
parent: 'app',
abstract: true,
views: {
'nav#app': { '...' },
'header#app': { '...' }
}
})
// In-app routes
.state('dashboard', {
parent: 'in-app',
url: '/app/dashboard'
views: {
'body#app': { '...' }
}
})
.state('users', {
parent: 'in-app',
url: '/app/users'
views: {
'body#app': { '...' }
}
})
.state('settings', {
parent: 'in-app',
url: '/app/settings'
views: {
'body#app': { '...' }
}
})
At the moment this works great, but for the in-app routes I would like to define a title that is displayed in the header#app view.
What would be the best way to do this? At the moment I can only think of either setting a variable on the $rootScope, or sending out an event. But for both of those I would need a controller.
Is there a way I could do this directly from my routes config?
The sample applicaiton of the UI-Router, uses this code:
ui-router / sample / app / app.js
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.For example,
// <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
// to active whenever 'contacts.list' or one of its decendents is active.
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
And that means, that with data : {} feature:
Attach Custom Data to State Objects
You can attach custom data to the state object (we recommend using a data property to avoid conflicts).
// Example shows an object-based state and a string-based state
var contacts = {
name: 'contacts',
templateUrl: 'contacts.html',
data: {
customData1: 5,
customData2: "blue"
}
}
we can do this:
.state('in-app', {
parent: 'app',
abstract: true,
views: {
'nav#app': { '...' },
'header#app': { '...' }
}
data: { title : "my title" },
})
And use it in some template like:
<div>{{$state.current.data.title}}</div>
Some summary.
We can place state and params into $rootScope, so we can access it without any controller anyhwere.
We can declare some more custom stuff via data and use it as a title ... anyhwere

Categories