由于某种原因,页面会自动刷新AngularJS

时间:2014-11-22 09:26:06

标签: javascript html angularjs

在我的应用程序中,每当我点击通过$ routeprovider加载不同部分的链接时,页面会定期刷新。然后,除了刷新之外,它还会将我带回默认的部分(即,我必须再次点击链接才能到达我想去的地方)。我根本没有使用任何刷新页面的方法;为什么会发生这种情况?

另外,有趣的是,当我点击任何非$ routeprovider链接时,这不会发生。以下是我的routeProvider:

.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: "index.html"
            }).
            when('/profile/:id', {
                templateUrl: "profile.html",
                controller: 'UsersController as profiledUser'
            }).
            when('/gift/:id', {
                templateUrl: "gift.html",
                controller: 'GiftsController as profiledGift'
            }).
            when('/users-form', {
                templateUrl: "users-form.html",
                controller: 'UsersController as newUser'
            }).
            when('/login-form', {
                templateUrl: "login-form.html",
                controller: 'UsersController as loginUser'
            }).
            when('/gifts-form', {
                templateUrl: "gift-form.html",
                controller: 'GiftsController as newGift'
            }).
            when('/about', {
                templateUrl: "about.html"
            }).
            otherwise({
                redirectTo: '/'
            });

以下是其中一个链接的示例,该链接在Chrome的开发工具中进行检查时链接到当前登录用户的个人资料:

<a href="#profile/5" data-ng-click="template=1" style="color: white;">Profile</a>

以下是代码中的相同链接,它是导航栏的一部分:

<li><a href="#profile/{{id}}" data-ng-click="template=1" style="color: white;">Profile</a></li>

重申一下,点击任何上述链接偶尔会重定向到.otherwise并刷新页面。我无法可靠地重现这种行为,因为它似乎是随机发生的;奇怪的是,即使我从配置中删除了.otherwise路线,也会发生这种情况。

1 个答案:

答案 0 :(得分:0)

看起来您点击<a>标签时一次尝试做两件事,但只发生了1件事:

  1. 默认操作,位于href中,并显示“加载UsersController +配置文件视图”和
  2. 在当前上下文中设置template=1
  3. 即使发生template=1,一旦切换到UsersController,您将无法再访问此设置。

    尝试这样的事情:

    <a href="#/profile/{{id}}/{{template}}">Profile</a>
    

    .when('/profile/:id/:template', {
      controller: 'UsersController as profiledUser',
      templateUrl: 'profile.html'
    })
    

    或者,使用$ rootScope或template=1的其他全局上下文,因此只要您依赖注入它,它就始终可用于任何控制器+视图。

相关问题