jacob jacob - 5 months ago 94
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: [
'$stateParams',
'validator',
function validateParamA($stateParams, validator) {
// return some value
}
}
}
}


However,
$stateParams
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
$stateParam
itself. So I'm looking for something like
urlRouterProvider.when
's
$match
.

My next idea was to just use a
urlRouterProvider.when
. 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).

Update



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

Answer

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;
}

$urlMatcherFactoryProvider.type(
    'locale',
    {
        pattern: ROUTING.localeRegex
    },
    [
        // …
        function localeFactory(validator, CONSTANTS) {
            return {
                encode: validateLocale.bind({}, validator, CONSTANTS)
            };
        }
    ]
);

:Rage:

Comments