ui-router $state.go VS ui-sref 让我在 AngularJS 中发疯 [英] ui-router $state.go VS ui-sref is making me nuts in AngularJS

查看:25
本文介绍了ui-router $state.go VS ui-sref 让我在 AngularJS 中发疯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 ui-sref 调用时有效

It works when called via ui-sref

<a class="button" ui-sref="main.create">

但是当使用 ng-click 和 $stage.go 调用它时,它会被调用并呈现页面,但我的 $urlRouterProvider.otherwise 将再次覆盖 DOM.我在一步一步调试的时候注意到了.它可能认为 main.create 是一个不存在的 url.

but when it's called using ng-click and $stage.go, it's called and renders the page but my $urlRouterProvider.otherwise will override the DOM again. I noticed it when I debugged step by step. It maybe thinks that main.create is a non-existent url.

这里是 ng-click 的代码和函数.

here is the code and function for ng-click.

<a href="#" ng-click="create()">Create Object</a>

这里是 create() 函数

and here is create() function

$scope.create = function() {
  $state.go('main.create');
};

当使用 ng-click="create()" 时,它正在调用 $state.go('main').但在它调用 $state.go('main') 之前,我在 DOM 中看到了正确的 main.create 页面渲染.我写了那个IF"语句来处理不存在的 url,以便它们被重定向回主页.这是我的 config.js.

It's calling $state.go('main') when ng-click="create()" is used. But before it calls $state.go('main'), I see the proper main.create page render in DOM. I wrote that "IF" statement to handle non-existent url so they get redirected back to main page. Here is my config.js.

  .state('main', {
    url: '/',
    views: {
      '@': {
        templateUrl: 'app/main/main.html',
        controller: 'MainController'
      },
      'content@main' : {
        templateUrl: 'app/main/main.display.html'
      }
    }
  })

  .state('main.create', {
    url: '/create',
    views: {
      'content@main' : {
        templateUrl: 'app/main/main.create.html'
      }
    }
  })

  $urlRouterProvider.otherwise(function ($injector) {
  var Session = $injector.get('Session');
  var $state = $injector.get('$state');
  if (Session.isAuthenticated()) {
    $state.go('main'); // <-- this is what gets called when using ng-click and after main.create partial gets rendered
  } else {
    $state.go('login');
  }
});

推荐答案

出现这种情况是因为您在同一个锚标记上触发了一个操作和一个路由.在 中,您不需要 hrefng-click 出现.将其更改为 <a ng-click="create()">,或者如果需要使用 href,请将其设置为空,例如 <a href="" ng-click="create()">.

This is occurring because you are triggering an action and a route on the same anchor tag. In <a href="#" ng-click="create()">, you don't need both href and ng-click to be present. change it to <a ng-click="create()">, or if having the href is necessary, set it to empty, like <a href="" ng-click="create()">.

这篇关于ui-router $state.go VS ui-sref 让我在 AngularJS 中发疯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆