How to programmatically create URLs with AngularJS

后端 未结 3 1449
旧时难觅i
旧时难觅i 2021-02-02 08:14

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

Now I would like to navigate inside m

3条回答
  •  眼角桃花
    2021-02-02 08:38

    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.

    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('&');
    }
    

提交回复
热议问题