第5篇:ui-router路由带参数跳转后controller执行两次的问题处理

最近用到了ui-router做项目:

跳转路由:

<a ui-sref="createOffer" class="third-item">Create Offer</a>
路由配置:
.state('createOffer', {
      url: "/offerManager/create/{id}",
      templateUrl: "./view/appOffer/offer/create/createOffer.html",
      controller:"createOfferCtrl"
})
路由跳转:

$state.go("createOffer",{id:getId});

但是当点击跳转时会发现页面对应的子controller执行了两次:


网上查的大部分都是因为controller在html中多写了一次的原因,但是这里的controller并没有第二次配置,几经折腾在github上找到了解决办法:

Let's say you have a state with an optional parameter :

.state('app.numbers', {
  url: '/numbers{timestamp:.*}',
  templateUrl: 'numbers/templates/app.numbers.html',
  controller: 'NumberListCtrl'
})
if you just use a link like this, the controller NumberListCtrl will be loaded twice, once with a timestamp parameter with an undefined value, and once with a '' value :

<a ui-sref=".numbers">numbers</a>

也就是说路由跳转了两次,一次是带参数执行的,另一次是为不带参数执行,当然上面也给了解决办法:

To prevent your controller from being loaded twice, you can use the following methods :

<a ui-sref=".numbers({timestamp:''})">numbers</a>
or use $state in js :

$state.go('app.numbers', {timestamp: ''});
or add these lines at the top of your controller :

// prevent double controller load because of the optional parameter
if (typeof $stateParams.timestamp === 'undefined') {
   return;
}

于是将路由改成这样:

<a ui-sref="createOffer({id : ''})" class="third-item">Create Offer</a>
再次跳转对应的controller就不会执行两次了。

参考:https://github.com/angular-ui/ui-router/issues/1476

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值