2014-10-10 52 views
1

我与未来的路线AngularJS应用:AngularJS,钩URL变化

/user/:userId 

用户打开

http://localhost/#/user/1 

在浏览器中。然后他在URL栏中将userId的值从1更改为2,然后按回车。

我的问题是:如何挂钩这一刻,不重新加载控制器?例如,我只想在同一页面上显示消息(或使用新的userId值做alert()或console.log())。

+0

https://github.com/angular-ui/ui-router/wiki#state-change-events – JoseM 2014-10-10 16:08:20

回答

1

您可以收听'$stateChangeStart' event并致电event.preventDefault()以防止用户实际转到新视图。

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 
    event.preventDefault(); 
    // transitionTo() promise will be rejected with 
    // a 'transition prevented' error 
}); 

注意,如果要添加控制器里面这个监听器,你应该保持在注销函数的引用,以便在你的范围被破坏,除去监听器。

var removeListenerFn = $rootScope.$on('$stateChangeStart', 
    function(event, toState, toParams, fromState, fromParams){ 
     event.preventDefault(); 
     // transitionTo() promise will be rejected with 
     // a 'transition prevented' error 
    } 
); 

    $scope.$on('$destroy',function(){ 
    removeListenerFn(); 
    }); 

下面是一个简单Plunker你可以用它来测试一下:http://plnkr.co/edit/lYfkPuePGv1GlN1sFjW4?p=preview