tolyasik tolyasik - 2 months ago 9
AngularJS Question

Getting view name inside of controller

I have the following configuration of state:

.state('main.content', {
url: '',
views: {
'content-one': {
templateUrl: 'templates/staging-area/content.html',
controller: 'ContentCtrl'
},
'content-two': {
templateUrl: 'templates/staging-area/content.html',
controller: 'ContentCtrl'
}
}
})


How can I get the name of view inside of controller?

Answer

You can access state configuration objects with the help of helper method $state.get() (link to docs). If you do not specify a route name as a first parameter, than it well return the entire configuration for all the routes.

app.controller('AppCtrl', function ($state) {

  var stateConfig = $state.get('main.content');

});

Update:

This seems to be a bit tricky and not a solid solution, but when you set a container for a view, you specify it's name directly like <div ui-view="content-one"></div>, so you could try to query this element which sets a view using:

var element = angular.element('[ui-view]');
var name = element.attr('ui-view'); // 'content-one'

But be aware that you may have multiple views on a page. So the following would be more safe:

<div class="main-content" ui-view="content-one"></div>

JS:

var element = angular.element('.main-content');
var name = element.attr('ui-view'); // 'content-one'
Comments