jacob jacob - 6 months ago 114
AngularJS Question

UI Router: How to validate parameter before state resolves

I've got a known list of supported values for parameter A. I need to validate the state parameter's value before any of the state's resolves are triggered, and if the value is invalid, to supply a supported value. My initial thought was to use an injectable function for the parameter's value property:

params: {
A: {
value: [
function validateParamA($stateParams, validator) {
// return some value

is unpopulated at this point (I was hoping for a preview version like what you get in a resolve), and also this would probably set a default value, not the value of the
itself. So I'm looking for something like

My next idea was to just use a
. No-dice: To my dismay, this fires after the state has resolved.

My next idea was to hijack urlMatcherFactory's encode. Same deal (fires after).


Ugh! The problem is that a controller is being executed outside of UI Router via
. Moving it inside should fix the sequence issue (and then
should work). Will update later today.


A MarcherFactory did the trick. After I corrected that ngController nonsense and brought those controllers inside UI Router, it worked just as I expected.

// url: '/{locale:locale}'

function validateLocale(validator, CONSTANTS, value) {
    var match = validator(value);

    if (match === true) {
        return value;

    if (match) { // partial match
        newLocale = match;
    } else {
        newLocale = CONSTANTS.defaultLocale;

    return newLocale;

        pattern: ROUTING.localeRegex
        // …
        function localeFactory(validator, CONSTANTS) {
            return {
                encode: validateLocale.bind({}, validator, CONSTANTS)