如何使 Angular ui-router 的父状态在状态更改时始终执行控制器代码?

假设我们在 $stateProvider 中定义了一个父子关系,如下所示:

Let's say we have a parent-child relationship defined in our $stateProvider as follows:

    .state('myProfile', {
        url: "/my/profile",
        templateUrl: 'my/profile.html',
        controller: 'MyProfileController'
    }).state('myProfile.edit', {
        url: "/edit",
        templateUrl: 'my/profile.edit.html',
        controller: 'EditMyProfileController'
    });

这里的想法是父 myProfile 状态是不可编辑的,但子 myProfile.edit 状态是编辑配置文件的实际表单.让我们忽略个人资料页面是否应该这样工作 - 我只是在玩弄东西和学习.

The idea here is that the parent myProfile state is non-editable, but the child myProfile.edit state is the actual form to edit the profile. Let's ignore if this is how a profile page should work - I'm just playing around with things and learning.

当用户提交表单时,我使用 $state 对象返回到父页面:

When a user submits the form, I use the $state object to go back to the parent page:

$scope.save = function() {
    userResource.update($scope.user, function() {
        SessionService.refresh();

        $state.go('myProfile'); // also tried with reload: true as well
    });
}

在用户保存配置文件数据后 - 正确保存 - 除非我按 F5 并刷新浏览器,否则父视图不会更新.

After the user saves the profile data - and it is getting saved properly - the parent's view does not get updated unless I hit F5 and refresh the browser.

我注意到的一件事是,如果我将子 myProfile.edit 状态设置为父状态,而不是 myProfile 状态的子状态,则此问题实际上会出现离开了,事情就按预期运行了(尽管这样的布局看起来很糟糕).

One thing I have noticed is that if I make the child myProfile.edit state into a parent itself and not a child of the myProfile state, this problem actually goes away and things behave as expected (albeit, the layout looks bad like this).

似乎 UI Router 可能正在缓存父级的结果,不知道模型中的事情发生了变化并且需要重新运行控制器?

It seems that UI Router is maybe caching the result of the parent, unsuspecting that things have changed in the model and that it needs to rerun the controller?

如何在保持父 myProfile 页面始终执行其控制器以重新加载其数据的同时保持我的父子关系?基本上,我希望在使用 $state 或单击指向 myProfile 的链接时发生这种情况.我该怎么做?

How can I keep my parent-child relationship while still having the parent myProfile page always execute its controller to reload its data? Basically, I want this to happen whenever $state is used or when a link is clicked that directs to myProfile. How can I do that?

如果我不能按照我的要求做,那么我知道我可以设置一堆子状态并让它们按预期工作......但是,我如何为父级设置默认子状态?例如,假设我希望 myProfile.edit 成为 myProfile 的默认子状态 - 我该怎么做?

And if I cannot do what I ask, then I am aware that I can setup a bunch of child states and have them work as intended... however, how can I set the default child state for the parent? For example, let's say I want myProfile.edit to be the default child state of myProfile - how can I do that?

谢谢!

推荐答案

要在从子状态导航到父状态时强制重新加载父状态,您可以使用以下两种方式.纯js或者指令属性.

To force a parent state to reload when navigate to him from a child state you can use both ways below. Pure js or a directive attribute.

<a ui-sref="myProfile" ui-sref-opts="{ reload: true }">Back to My Profile</a>

$state.go('myProfile', null, { reload: true });

相关文章