最近用到了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