Angular/UI-Router - 如何在不刷新页面的情况下更新URL?

17

我对Angular和ui-router都不熟悉。当有人选择一个模型并且我的控制器执行标准的SHOW方法时,我只想更新URL以包括模型的ID而不刷新页面,并继续使用原始视图。我不确定该如何做到这一点...

$stateProvider
        .state('citylist', {
          url: "/",
          templateUrl: "views/index.html"
        })
        .state('cityshow', {
          url: "/city/:id",
          templateUrl: "views/index.html"
        })

angular.module('app.system').controller('IndexController', ['$scope', 'Global', 'Cities', '$stateParams', '$location', function ($scope, Cities, $stateParams, $location) {

    $scope.loadTown = function(id) {
        Cities.get({id: id }, function(city) {
             $scope.city = city
             // Change URL
             // Do things within the same view...
        });
    };
});

<button ng-click="loadTown(123456)">Chicago</button>
2个回答

6
您使用的代码片段与正确的ui-router设置有些偏差。我建议您查看此演示应用程序:http://angular-ui.github.io/ui-router/sample/#/contacts/1。在这里,我们可以看到如何在不刷新页面的情况下“固定”列表,而更改详细信息。
此示例的代码在此处下载:https://github.com/angular-ui/ui-router/tree/master/sample
对于理解如何(除了wiki以外)非常有帮助的是这个代码片段:state.js。加载演示,阅读此评论解释。然后,ui-router就会有意义...

2
我相信你已经看过这个链接:http://egghead.io/lessons/angularjs-introduction-ui-router。Radim的建议很好。大多数的jsfiddles、plunkers和文章都已经过时了,虽然ui-router并不是真的很难,但除非你找到正确的来源,否则需要一段时间才能意识到它的重要性。 - scalaGirl
@radim:这真的解决了原始问题吗 - 即如何更新模型和URL,但不刷新视图?这就是我在https://dev59.com/DF4c5IYBdhLWcg3w1tWO重新提出的问题。 - Simon H

1
实质上,您想要做的是在ui-view中放置城市代码和/或不使用具有此视图的模板。结果,DOM的任何部分都不会发生变化,但URL会发生变化。这在Angular-ui.router: Update URL without view refresh上有更详细的讨论。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接