AngularJS $ location.path的问题

时间:2014-03-28 15:03:48

标签: angularjs angularjs-routing

我正在玩带有麻烦的AngularJS路线的乐趣和游戏,所以让我们看看能否解释这个问题。

APP.JS:

app = angular.module("index", []);

app.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/booking/damage/:regnumber', {
                templateUrl: 'damage',
                controller: 'DamageCtrl'
        }).
            otherwise({
                redirectTo: '/'
        });
    }
]);

app.controller('IndexCtrl', function($scope, $location) {
    $scope.regnumber = '';
    $scope.progress = function() {
        if ($scope.regnumber !== '') {  
            $location.path('/booking#/damage/' + $scope.regnumber);
        } else {
            $location.path('/booking#/damage');
        }
    };
});

我的初始页面的路径为

http://localhost/windscreens/glass/index#/index

在此页面中是一个表单,通过ng-submit="progress()调用我的IndexCtrl控制器中的$ scope.progress函数。有一个字段形式为ng-model =" regnumber"。

因此,当填写输入字段时,请说" ABC"然后点击按钮,我希望路径成为:

http://localhost/windscreens/glass/booking#/damage/ABC

但它变成了

http://localhost/windscreens/glass/index#/booking%23/damage/ABC

事情是我仍然真的习惯了Angular路由系统并且还没有得到它。对此有任何建议将不胜感激!

为什么我看到我所看到的?我在这里遇到了什么错误?

2 个答案:

答案 0 :(得分:2)

Angular $ routeProvider只能在哈希(#)之后更改URL的一部分,因此在调用$location.path()时,您只需使用您在{的路由中定义的普通URL片段{1}}。

一些解释

我将在这里简化一下,但希望它能帮助你理解正在发生的事情。

您正在制作SPA(单页应用),因此您在浏览器中输入的用于进入应用的网址在您在路线之间导航时不会发生变化;默认情况下,$ routingProvider将DamageCtrl附加到该基本URL。在您的情况下,您似乎在名为#/whatever/route的文件中有入口点(ng-app),因此所有路径都将附加到该文件中。

由于您没有定义我们可以看到的/windscreens/glass/index路由,因此我不确定/index是如何为您工作的。它应该会将您转到http://localhost/windscreens/glass/index#/index,因为您的http://localhost/windscreens/glass/index#/路由只是otherwise

回到问题

如果我正确理解了您的问题,我会制作索引文件(/生活在哪里)ng-app,然后您只需输入/windscreens/glass/index.html即可进入应用,因为网络服务器默认情况下会提供index.html的内容。

此时,您的索引页网址将变为http://localhost/windscreens/glass/,您的http://localhost/windscreens/glass/#/路由将为/booking/damage/等。导航到它们的代码将是

http://localhost/windscreens/glass/#/booking/damage/ABC

答案 1 :(得分:2)

角度路由会更改页面上的路由;它没有带你到一个新的目录或页面。

因此,如果index.html包含您的Angular应用,并且您有"预订","预订","取消"等等的路线。您'最终会看到如下的网址:

/glass/index.html#/booking
/glass/index.html#/reservation
/glass/index.html#/cancellations

该路线仅仅附加到index.html。

因此,从某种意义上说,您的路线工作正常。您看到添加的%23是网址编码#

如果您在/glass/booking找到了第二个Angular应用,并且您尝试将用户转发给它,则可以使用$window.location.hash$window.location.pathname。例如,

$window.location.hash = "/damage/ABC";
$window.location.pathname = "/windscreens/glass/booking";
should take you to:
/windscreens/glass/booking#/damage/ABC
相关问题