在我的用例中,有三个,因为没有更好的词,“视图”。第三个视图中显示的内容取决于在第二个和第一个视图中所做的选择。类似地,在第二个视图中显示的子主题取决于在第一个视图中所做的选择。
Select Topic | Select Subtopic | Display Content
------------------------------------------------------
Vegetables   | Apple           | The peach is a tasty
FRUITS*      | Banana          | fruit that has a nice
Meats        | PEACH*          | color, etc.
Fish         |                 |目前,当用户选择一个主题时,我会获取并显示子主题列表。一旦用户选择了一个子主题,我就会获取并显示该内容。到目前为止,一切顺利。
唯一的问题是,我也希望用户能够通过导航到表单的url来访问:
example.com/index.html#/topic/subtopic我让它工作,以便导航到url导致所有正确的内容被加载。这不是问题所在。
我的问题是,如果用户选择了一个新的主题或副主题,我想要更改url。但不会导致页面重载(这似乎就是我使用location.path时所发生的情况。我该怎么做呢?
发布于 2014-07-07 05:41:07
您不应该使用window的location.path,而应该使用Angular的路由(通过$location.path()或隐式更改#hash)。
使用这样的视图:
<!-- Categories -->
<script type="text/ng-template" id="partials/categories.tmpl.html">
    <h3>Select a food category:</h3>
    <ul>
        <li ng-repeat="category in categories">
            <a ng-href="#/{{category.path}}">{{category.label}}</a>
        </li>
    </ul>
</script>
<!-- Fruits -->
<script type="text/ng-template" id="partials/fruits.tmpl.html">
    <h3>Select a fruit:</h3>
    <ul>
        <li ng-repeat="fruit in fruits">
            <a ng-href="#/fruits/{{fruit.path}}">{{fruit.label}}</a>
        </li>
    </ul>
    <a ng-href="#/{{back}}">Back</a>
</script>
<!-- Meats --->
...
<!-- Vegetables -->
...
<!-- Description -->
<script type="text/ng-template" id="partials/description.tmpl.html">
    <h3>{{item}}</h3>
    <p>{{description}}</p>
    <a ng-href="#/{{back}}">Back</a>
</script>适当的控制器和服务以及类似如下的配置:
function config($routeProvider) {
    $routeProvider.
        when('/', {
            templateUrl: 'partials/categories.tmpl.html',
            controller:  'categoriesCtrl'
        }).
        when('/fruits/:fruit?', {
            templateUrl: function (params) {
                return params.fruit ?
                        'partials/description.tmpl.html' : 
                        'partials/fruits.tmpl.html';
            },
            controller:  'fruitsCtrl'
        }).
        when('/meats/:meat?', {...}).
        when('/vegetables/:vegetable?', {...}).
        otherwise({
            redirectTo: '/'
        });
}你可以实现你想要的!
另请参见此。
发布于 2014-07-07 02:19:04
据我所知,实现这一点的唯一方法是使用ui-router。
使用ngrouter时,您必须更改查询字符串参数的参数,因此如下所示:
example.com/index.html#/myRoute?topic=topic&subtopic=subtopic然后在你的路由配置中:
when('/myRoute', { templateUrl: ..., reloadOnSearch: false })然后,您将在控制器上侦听路由($routeChangeSuccess)上的更改,并从中获取查询字符串。
https://stackoverflow.com/questions/24598500
复制相似问题