在ui.router中更改$ state.go()的默认行为以默认重新加载

rme*_*ger 10 angularjs angular-ui-router

我有一个使用ui.router包构建的Angular应用程序用于URL路由.我想更改它,以便如果用户尝试导航到他们已经在的页面,路由器将重新加载该状态而不是什么都不做.根据http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$ state#go,$ state.go 确实采用了一个重新加载参数,但是这样做的确如此它默认为false.现在,在我的代码中重写每个调用$ state.go和每个ui-sref以将reload设置为true的想法都是一个糟糕的想法.我想要的是改变$ state.go的那个参数的默认值的一些方法,或者至少是ui-sref装饰器.

http://angular-tips.com/blog/2013/09/experiment-decorating-directives/之后,我尝试至少扩展ui-sref指令(因为除了明确的指令之外还有更多的指令) $ state.go电话)

myApp.config(function($provide) {
    // override ui-sref to have the reload option default to true.
    $provide.decorator('uiSrefDirective', function($delegate){
        var directive = $delegate[0];
        var link = directive.link;

        directive.compile = function() {
            return function(scope, element, attrs) {
                if(attrs.uiSrefOpts == null){
                    attrs.uiSrefOpts = {};
                }

                if(attrs.uiSrefOpts.reload == null){
                    attrs.uiSrefOpts.reload = true;
                }
                console.log(arguments);

                link.apply(this, arguments);
            };
        };
        return $delegate;
    });
Run Code Online (Sandbox Code Playgroud)

然而,这实际上似乎没有任何成就,即使它确实如此,它实际上也不会影响$ state.go.有没有人有任何想法如何在ui.router代码中手动更改这种行为?

Rad*_*ler 19

我在下面调整了你的方法.我们将从装饰中获益,但不会从指令中获益.我们可以在这里查看,在ui-sref指令源代码中,click事件实际上会调用:

$state.go(ref.state, params, options); 
Run Code Online (Sandbox Code Playgroud)

所以,我们可以装饰$state提供者,这可能非常简单:

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

        // let's locally use 'state' name
        var 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' decoration
        var go = function (to, params, options) {
            options = options || {};

            // only in case of missing 'reload'
            // append our explicit 'true'
            if (angular.isUndefined(options.reload)) {

                options.reload = true;
            }

            // 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;
    });        
})
Run Code Online (Sandbox Code Playgroud)

这就够了.现在任何状态变化(包括点击ui-sref)都会触发reload.

注意:只是必须说,我不认为这是这样的.触发重装一直......对我来说,似乎我们实际上已经松了一口气,松散了钻石带来的优势 - ui-router