Skip to content Skip to sidebar Skip to footer

How To Inject State Parameter Automatically

Abstract Hi, I'm using angular + ui-router in my project, I have huge amount of nested states and different views that in turn contain huge amount of different inputs, a user fills

Solution 1:

The AOP and Decorator pattern are the answer. The comprehensive description could be found here:

Experiment: Decorating Directives by Jesus Rodriguez

Similar solution as described below, could be observed:

Changing the default behavior of $state.go() in ui.router to reload by default

How that would work? There is a link to working example

In this case, we do not solve from which source the random GUID comes from. Let's just have it in runtime:

var guidFromSomeSource = '70F81249-2487-47B8-9ADF-603F796FF999';

Now, we can inject an Decorator like this:

angular
.module('MyApp')
.config(function ($provide) {
    $provide.decorator('$state', function ($delegate) {

        // let's locally use 'state' namevar state = $delegate;

        // let's extend this object with new function // 'baseGo', which in fact, will keep the reference// to the original 'go' function
        state.baseGo = state.go;

        // here comes our new 'go' decorationvar go = function (to, params, options) {
            params = params || {};

            // only in case of missing 'id'// append our random/constant 'GUID'if (angular.isUndefined(params.id)) {

                params.id  = guidFromSomeSource;
            }

            // return processing to the 'baseGo' - original
            this.baseGo(to, params, options);
        };

        // assign new 'go', right now decorating the old 'go'
        state.go = go;

        return$delegate;
    });        
})

Code should be self explanatory, check it in action here

Post a Comment for "How To Inject State Parameter Automatically"