Javascript 如何使用 AngularJS 以编程方式创建 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12808779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:31:22  来源:igfitidea点击:

How to programmatically create URLs with AngularJS

javascripthtmlangularjs

提问by Marc

Currently I am toying with the AngularJS framework. I'm using the $route service for deep linking into my single-page application.

目前我正在玩弄 AngularJS 框架。我正在使用 $route 服务深度链接到我的单页应用程序。

Now I would like to navigate inside my application, say, by changing just the search part of the current URL. It is easy to do using the $location service in JavaScript, but how can I construct an href attribute from the current route with just the search part replaced?

现在,我想在我的应用程序中导航,例如,只更改当前 URL 的搜索部分。在 JavaScript 中使用 $location 服务很容易,但是如何从当前路由构建一个 href 属性,只替换搜索部分?

Do I have to do it by hand or is there an AngularJS way for it?

我必须手动完成还是有 AngularJS 的方法?

Added:

添加:

Of course, the $location service has all methods to calculate such URLs. But I cannot use it because $location does also navigate the browser window to the new URL.

当然,$location 服务拥有计算此类 URL 的所有方法。但是我不能使用它,因为 $location 也会将浏览器窗口导航到新的 URL。

There is another complication with creating URLs by hand: One has to check whether the legacy #-method or the new History API is used. Depending on this, the URL has to include a #-sign or not.

手动创建 URL 还存在另一个复杂性:必须检查是否使用了传统的 #-method 或新的 History API。根据这一点,URL 必须包含或不包含 # 符号。

回答by Delian Mitankin

Starting from v1.4 you can use $httpParamSerializerfor that:

从 v1.4 开始,您可以使用$httpParamSerializer

angular.module('util').factory('urlBuilder', function($httpParamSerializer) {
    function buildUrl(url, params) {
        var serializedParams = $httpParamSerializer(params);

        if (serializedParams.length > 0) {
            url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
        }

        return url;
    }

    return buildUrl;
});

Usage:

用法

To produce http://url?param1=value1&param2=value2_1&param2=value2_2call it with:

生产http://url?param1=value1&param2=value2_1&param2=value2_2调用它:

urlBuilder('http://url', { param1: 'value1', param2: ['value2_1', 'value2_2'] });

回答by synergetic

Following Robert's answer, I found the functions in Angular.js. They are buildUrl, forEachSorted, and sortedKeys. builUrl also uses isObject and toJson functions, which are public, so they must be changed to angular.isObject and angular.toJson respectively.

按照罗伯特的回答,我在 Angular.js 中找到了这些函数。它们是 buildUrl、forEachSorted 和 sortedKeys。builUrl 还使用了 isObject 和 toJson 函数,它们是公共的,因此必须将它们分别更改为 angular.isObject 和 angular.toJson。

function forEachSorted(obj, iterator, context) {
    var keys = sortedKeys(obj);
    for (var i = 0; i < keys.length; i++) {
        iterator.call(context, obj[keys[i]], keys[i]);
    }
    return keys;
}

function sortedKeys(obj) {
    var keys = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            keys.push(key);
        }
    }
    return keys.sort();
}

function buildUrl(url, params) {
    if (!params) return url;
    var parts = [];
    forEachSorted(params, function (value, key) {
        if (value == null || value == undefined) return;
        if (angular.isObject(value)) {
            value = angular.toJson(value);
        }
        parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
    });
    return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}

回答by Robert

As you can see in the source code here (v.1.1.0):

正如您在此处的源代码中所见(v.1.1.0):

https://github.com/angular/angular.js/blob/v1.1.0/src/ngResource/resource.js#L228

https://github.com/angular/angular.js/blob/v1.1.0/src/ngResource/resource.js#L228

and here:

和这里:

https://github.com/angular/angular.js/blob/v1.1.0/src/ngResource/resource.js#L247

https://github.com/angular/angular.js/blob/v1.1.0/src/ngResource/resource.js#L247

Angularjs doesn't use internally encodeURIComponentfor managing URI strings but neither make available the used functions. These functions are internal to the module (what I think is a pity).

Angularjs 不使用内部encodeURIComponent来管理 URI 字符串,但也不提供使用过的函数。这些函数是模块内部的(我觉得很可惜)。

If you want to manage your URIs in exactly the same way that AngularJS, maybe you can copy these functions from the source to your code and make your own service for that.

如果您想以与 AngularJS 完全相同的方式管理您的 URI,也许您可​​以将这些函数从源代码复制到您的代码中,并为此创建您自己的服务。