问题
If I am working with href, UI Router works as expected. But, if I am using ui-sref, it is not working as expected.
I have two issue with the following example:
- the anchors 'link-series-2-no-param' and 'link-series-2-one-param' do not trigger 'otherwise' (they do in 'link-series-1'). What to do if they need to go to 'otherwise'?
- if you click all 'link-series-2' and do the same in reverse, it's not going to work (always shows the result of 'link-series-2-two-params', even if you click on others)
a01.htm:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.min.js" ></script>
<script type="text/javascript" src="a01.js"></script>
...
<a ui-sref='root'>Home</a>
<br>
<a href='#/demo1/'>link-series-1-no-param</a>
<a href='#/demo1/30'>link-series-1-one-param</a>
<a href='#/demo1/30/40'>link-series-1-two-param</a>
<br>
<a ui-sref-opts="{reload: true, notify: true}" ui-sref='demo1'>link-series-2-no-param</a>
<a ui-sref-opts="{reload: true, notify: true}" ui-sref='demo1({a: 30})'>link-series-2-one-param</a>
<a ui-sref-opts="{reload: true, notify: true}" ui-sref='demo1({a: 30, b:40})'>link-series-2-two-param</a>
<hr>
<div ui-view></div>
a01.JS:
var app = angular.module('app', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$stateProvider
.state('demo1', {
url: '/demo1/:a/:b',
templateUrl: 'demo1.htm',
controller: 'demo1'
})
.state('root', {
url: '/',
template: '<strong>you are at root..click something else</strong>'
});
$urlRouterProvider.otherwise("/");
}]);
app.controller('demo1', ['$scope', '$stateParams', function($scope, $stateParams){
$scope.a = $stateParams.a;
$scope.b = $stateParams.b;
console.log('a = ' + $stateParams.a + ', b = ' + $stateParams.b);
}]);
demo1.htm:
<div>
a = {{a}}, b = {{b}}
</div>
What am I missing in the above sample?
回答1:
The behaviour experienced in this case, is coming from a fact that we use an $state.go
option : { reload: true }
<a ui-sref-opts="{reload: true ...
Check the doc https://ui-router.github.io/docs/0.3.1/#/api/ui.router.state.$state#methods_go
reload (v0.2.5) - {boolean=false|string|object}, If true will force transition even if no state or params have changed. It will reload the resolves and views of the current state and parent states...
And in this example, we can see, that any ui-sref
, even with missing params, is navigated to... because it was forced
But, if we will use the default (native) approach, that state is reloaded only if there is any change (e.g. parameter change).
That example shows that in action
<a ui-sref-opts="{reload: false ...
Until any of params is changed - no state change is triggered. Hope that helps a bit...
来源:https://stackoverflow.com/questions/41429784/ui-sref-of-angular-ui-router-not-working-as-expected