1

您如何在不更改 URL/路由的情况下导航视图/部分?我只想要一个 URL,以便没有浏览器历史记录返回/下一个。

我尝试了 UI-Route,基本上可以满足我的要求,但是一旦我使用 $apply 方法查看视图,地址栏就会从“someapp.com”变为“someapp.com/#/”。它出现在 angular 1.1.5 中,但不是 1.0.7 并且仅在 hashbang 模式下。如何摆脱此 URL 更改?

谢谢!

编辑:我可以解决问题,现在使用 ui-router 完成该任务。

4

1 回答 1

2

您可以在没有路线的情况下控制一切。但是,如果您想要多个控制器,则必须广播共享事件。我的示例使用嵌套控制器方法。

看法:

<div ng-controller="mainCtrl">
    <ul class="nav nav-pills">
        <li ng-class="{active: activeView.view1}">
            <a href="javascript:" ng-click="setView('view1')"> View1 </a>
        </li>
        <li ng-class="{active: activeView.view2}">
            <a href="javascript:" ng-click="setView('view2')"> View2 </a>
        </li>
        <li ng-class="{active: activeView.view3}">
            <a href="javascript:" ng-click="setView('view3')"> View3 </a>
        </li>
    </ul>

    <div>
        <div ng-show="activeView.view1">
            <div ng-controller="view1Ctrl">
            ....
            </div>
        </div>
        <div ng-show="activeView.view2">
            <div ng-controller="view2Ctrl">
            ....
            </div>
        </div>
        <div ng-show="activeView.view3">
            <div ng-controller="view3Ctrl">
            ....
            </div>
        </div>
    </div>
</div>

然后在mainCtrl中:

//Handles the main view set function and broadcasts down to sub-controllers
$scope.setView = function(view) {
    $scope.activeView = {
        view1: false,
        view2: false,
        view3: false
    }
    $scope.activeView[view] = true;
    $scope.$broadcast('setView', view);
};

//Catches the reset view call from sub-controllers and re-broadcasts down
$scope.$on('viewReset', function(scope, view, msg) {
    $scope.setView(view, msg);
})

在 subCtrls 中:

//Catches the broadcast down and sets vars locally.
$scope.$on('setView', function(scope, view) {
    $scope.activeView = {
        view1: false,
        view2: false,
        view3: false
    }
    $scope.activeView[view] = true;
});

//Emits the message up to the mainCtrl to reset the view in all controllers
$scope.setView = function(view) {
    $scope.$emit('setView', view);
};
于 2013-05-30T15:38:36.980 回答