AngularJS 重新初始化控制器 [英] AngularJS reinitialize controller

查看:37
本文介绍了AngularJS 重新初始化控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 newGroupCtrl 的控制器,其定义如下:

I have got a controller named newGroupCtrl whose definition is like :

.state('new_group', {
    url: '/new_group',
    templateUrl: 'templates/new_group.html',
    controller: 'newGroupCtrl'
})

.controller('newGroupCtrl', function ($scope, $rootScope,$ionicHistory,$window) {
    $rootScope.roomId = $scope.getRoom();

    $scope.getRoom = function () {
        var date = new Date;
        var minutes = date.getMinutes();
        var hour = date.getHours();
        return 'room_' + hour + '' + minutes;
    };
}

我通过以下方式从上一页到达此控制器:

I reach this contoller from previous page by :

$window.location.href = ('#/new_group');

到现在为止都很好.$rootScope.roomId 变量在 newGroupCtrl 控制器中正确初始化.

That's good until now. $rootScope.roomId variable is initialized in the newGroupCtrl controller properly.

从这个 new_group 页面,我导航到另一个页面.当我通过调用 $window.location.href = ('#/new_group'); 导航回此页面时,$rootScope.roomId 不会再次初始化,而是它的旧值仍然存在.newGroupCtrl 的状态被保留.

From this new_group page, I navigate to another page. And when I navigate back to this page by calling $window.location.href = ('#/new_group');, $rootScope.roomId is not initialized again, instead its old value is still there. The state of the newGroupCtrl is preserved.

如何完全重新初始化 newGroupCtrl?

How can I completely reinitialize newGroupCtrl?

推荐答案

你需要在每次通过浏览器访问 URL 时告诉 state 重新加载控制器,只需添加 reload 状态为 true 的选项,如 reload: true.

You need to tell state that reload controller each time when URL is getting accessed via browser by just adding adding reload option of state to true like reload: true.

代码

.state('new_group', {
    url: '/new_group',
    templateUrl: 'templates/new_group.html',
    controller: 'newGroupCtrl',
    reload: true //will reload controller when state is being access
});

您应该使用 $state.go('new_group') 而不是执行 $window.location.href = ('#/new_group'); 这将确保路由更改将被 ui-router 识别.

You should use $state.go('new_group') instead of doing $window.location.href = ('#/new_group'); which will ensure that the route changes will recognize by ui-router.

相同的SO 答案在这里

这篇关于AngularJS 重新初始化控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆