angularjs ui-router default child state and ui-sref

二次信任 提交于 2019-12-17 22:49:09

问题


I have the following states in my ui-router state provider:

$urlRouterProvider.when('/parent', '/parent/child');
$stateProvider.state('parent', {
     url: "/parent",
     abstract: true
});

$stateProvider.state('parent.child', {
     url: "/child"
});

Which follows the best practice for having a default child state as explained here in the ui-router docs.

However, when I now include a link in my document somewhere referencing parent with ui-sref such as <a ui-sref="parent">Link</a> I always get an error saying I cannot transition to an abstract state. When I enter the URL manually into the address bar and hit enter everything works fine.

Related Plunker: http://plnkr.co/edit/d3Z0tOwC3VCTPqGiB0df?p=preview

How can I combine ui-sref with default child states?


回答1:


abstract states can not be targeted directly. They mainly serve as a foundation to build child states on. The only reason it works fine with the URL is that the /parent gets caught by the .when

That means when you invoke a child using

<a ui-sref="parent.child">

the child inside the parent gets loaded, meaning the parent will be loaded as the layer around it.

So, never target an abstract state itself. It's like having a door inside a door frame. You can only open and interact with the door (child), but never with the frame (parent) directly. However, when you interact with the door, the door and the frame are part of a system that gets loaded.

You can give the child an empty URL, so that it doesn't append anything to the parent state URL and will then be loaded.

See here for more info: https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#abstract-states




回答2:


If you want to use $state's convenient naming structure for abstract states, you can use this in a service:

$location.path(
    $state.href('app.some.abstract.state', { some: 'params' })
);

Or this in a template ($state must be available in the local or global $scope):

<a ng-href="{{$state.href('app.some.abstract.state', { some: 'params' })}}">...</a>

If I found myself doing this regularly, I would create a directive similar to ui-sref for this, minus the abstract state limitation.



来源:https://stackoverflow.com/questions/24969441/angularjs-ui-router-default-child-state-and-ui-sref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!