Skip to content

Instantly share code, notes, and snippets.

@stryju

stryju/Readme.md

Last active Aug 29, 2015
Embed
What would you like to do?
check if current function is a controller for current active state

ui.router's $state decorator

adding $state.controlledBy( controller[, state_name ]) function.

how could this be useful

well, if you want to see if the current state is the "last valid state", that's not a parent of currently active state.

sample:

given states (controllers will be referred with tne same name):

  • a
  • a.a1
  • a.a1.a2

when current state is a.a1.a2, $state.controlledBy( ctrl ) will return true only for a.a1.a2's controller

(function (ng, undefined) {
'use strict';
// jshint latedef:false
ng.module( 'foo', ['ui.router'] )
.config( config );
// @ngInject
function config( $provide ) {
$provide.decorator( '$state', decorator );
}
// @ngInject
function decorator( $delegate ) {
// jshint validthis:true
// jshint latedef:false
$delegate.controlledBy = controlledBy;
return $delegate;
// ---
function controlledBy( controller, state ) {
var constructor;
state = state || this.current;
if ( state.views ) {
return Object.keys( state.views )
.some( function ( view ) {
constructor = unwrap( state.views[ view ].controller );
return constructor && controller instanceof constructor;
});
}
constructor = unwrap( state.controller );
return constructor && controller instanceof constructor;
}
}
function unwrap( entity ) {
if ( ! Array.isArray( entity ) ) {
return entity;
}
return entity[ entity.length - 1 ];
}
})(angular);
function someStateController( $state ) {
console.log( $state.controlledBy( this ) ); // will check agains $state.current state
console.log( $state.controlledBy( this, 'specificState' ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment