ui-router 用$state.go时controller会跑两次

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <title>Ui State Demo</title>
        <meta charset="utf-8">

        <!--AngularJS v1.5.9-->
        <script type="text/javascript" src="angular.min.js"></script>

        <!--angular-ui-router v1.0.3-->
        <script type="text/javascript" src="angular-ui-router.min.js"></script>

        <script type="text/javascript">
            var app = angular.module('uiDemo', ['ui.router']);
            app.config(function($stateProvider) {
                $stateProvider.state('parent', {
                    url: '/parent',
                    controller: 'ParentController'
                }).state('parentChildOne', {
                    controller: 'ChildOneController',
                    template: '<h1>Child One</h2>'
                }).state('parentChildTwo', {
                    controller: 'ChildTwoController',
                    template: '<h1>Child Two</h2>'
                });
            });
            app.controller('ParentController', ['$state', function($state) {
                console.log('Parent Controller Start');
                if (Math.round(Math.random()) == 0) {
                    $state.go('parentChildOne');
                } else {
                    $state.go('parentChildTwo');
                }
            }]);
            app.controller('ChildOneController', ['$state', function($state) {
                console.log('Child One');
            }]);
            app.controller('ChildTwoController', ['$state', function($state) {
                console.log('Child Two');
            }]);
        </script>
    </head>
    <body ng-app="uiDemo">
        <nav>
            <a ui-sref="parent">Parent</a>
        </nav>

        <ui-view></ui-view>
    </body>
</html>

当点击“Parent”时,ParentController会跑两次(打出两次console.log('Parent Controller Start'))。有遇到过这个问题的么?

阅读 4.3k
2 个回答

调用两次是因为在代码中出现了2次跳转,第一次是加载parent这个Url,第二次是parentChildOne或者parentChild中的一个,但是配置文件中parentChildOne,和parentChildTwo 中url又缺失,所以就相当于重载了一次页面,而重载上次的url,上次的url没有变化,相当于重新读取了parent这个url。因此调了两次!
处理办法有两种:

1.分别对parentChildOne,parentChildTwo配置url参数(最好解决办法)
2.去掉parent里面的url参数,或者将url配置的值和parent名称对应值一样,即去掉url中parent前面的斜杠,保证和state中的str相等。为什么会这样,我估计ui-rotue在实现的时候先去找state对象上对应的str配置参数,在与相对应的url参数,如果url参数不存在则设置为str,当两者相等的时候则不进行跳转和刷新页面。

你在html上有没有配置ng-controller="ParentController" ? 路由和html只要配置一处即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进