在不同 templates/views 之间切换

Switch among different templates/views

我想为我的内容提出两种布局(即 horizontalvertical)。因此切换选择器将自动导致相应的布局。我当前的 JSBin 无法完成此切换:

<html ng-app="flapperNews">
<head>
    <script src="https://code.jquery.com/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
    <script type="text/ng-template" id="horizontal.tpl">
        {{one}}, {{two}}
    </script>
    <script type="text/ng-template" id="vertical.tpl">
        {{one}}<br>{{two}}
    </script>
    <script>
    var app = angular.module('flapperNews', ['ui.router']);

    app.config(['$stateProvider', function ($stateProvider) {
        $stateProvider
            .state('entry', {
                url: '/',
                templateUrl: "vertical.tpl"
            })
    }]);

    app.controller('MainCtrl', ['$scope', '$state', function ($scope, $state) {
        $scope.one = "one";
        $scope.two = "two";
        $scope.layouts = ["horizontal", "vertical"];
        $scope.$watch('layout', function () {
            $state.go('entry'); // need to amend this such that changing "layout" leads to different template
        })
    }])
    </script>
</head>

<body ng-controller="MainCtrl">
    <select ng-model="layout" ng-options="x for x in layouts"></select>
    <br><br>
    <ui-view></ui-view>
</body>

</html>

此外,我希望解决方案不会在 URL 中显示布局信息;用户只能在网页中查看和选择布局。此外,我不希望根据选择通过 SHOWING/HIDING <ui-view="horizontal"></ui-view>"<ui-view="vertical"></ui-view> 解决方案。我更喜欢将布局信息传递给状态以选择相应模板的解决方案(但不在 URL 中公开)。

有人知道怎么做吗?

  • 使用 non-url 参数,例如 layout
  • 使用 templateUrl 函数选择模板。

    app.config(['$stateProvider', function ($stateProvider) {
        $stateProvider
            .state('entry', {
                url: '/',
                params: { layout: 'vertical' },
                templateUrl: function(params) { 
                  return params.layout + ".tpl";
                }
            })
    }]);
    

然后您可以使用 state.goui-sref

进行切换

ui-sref="entry({ layout: 'horizontal' })"