Wednesday, 15 April 2015

angular ui router - How to get the controller's state name? -



angular ui router - How to get the controller's state name? -

i want know state's name controller configured, not current state.

notice on next jsfiddle i'm initiating route using location.hash , passing desired state name using resolve mechanism want avoid:

http://jsfiddle.net/coma/xzkh3kd5/

location.hash = '/a/b/c'; var template = '<div><h2>{{ current }} vs {{ wanted }}</h2><ui-view></ui-view></div>'; var app = angular.module('app', ['ui.router']); app.config(function ($stateprovider, $urlrouterprovider) { $urlrouterprovider.otherwise('/a'); $stateprovider .state('a', { url : '/a', template : template, controller: 'default', resolve : { wanted: function () { homecoming 'a'; } } }) .state('a.b', { url : '/b', template : template, controller: 'default', resolve : { wanted: function () { homecoming 'a.b'; } } }) .state('a.b.c', { url : '/c', template : template, controller: 'default', resolve : { wanted: function () { homecoming 'a.b.c'; } } }) ; }); app.controller('default', function ($scope, $state, wanted) { $scope.current = $state.current.name; $scope.wanted = wanted; });

well, have nice workaround this, , adding wanted state name while configuring states using inheritance:

a) iterating array of states configs

http://jsfiddle.net/coma/xzkh3kd5/1/

states.foreach(function (state) { var controller = state.config.controller; state.config.controller = function ($scope, $controller) { $scope.wanted = state.name; angular.extend(this, $controller(controller, { $scope: $scope })); }; $stateprovider.state(state.name, state.config); });

b) overriding state method

http://jsfiddle.net/coma/xzkh3kd5/2/

var state = $stateprovider.state; $stateprovider.state = function (name, config) { var controller = config.controller; config.controller = function ($scope, $controller) { $scope.wanted = name; angular.extend(this, $controller(controller, { $scope: $scope })); }; homecoming state.apply($stateprovider, arguments); };

looking towards improve solution.

angular-ui-router

No comments:

Post a Comment