简体   繁体   English

如何通过angularjs中的查询参数重定向url?

[英]How to redirect url by query parameters in angularjs?

I'm using ngRoute in angularjs to delegate different html templates, eg: 我使用ngRouteangularjs委托不同的HTML模板,例如:

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/cars', {
        templateUrl: 'partials/car-detail.html',
        controller: 'CarDetailCtrl'
      });

    //many more routes
  }]);

Problem: I want to have a common url, like localhost/my-app?myparam=Nokia . 问题:我想拥有一个通用网址,例如localhost/my-app?myparam=Nokia

I want to compare the myparam to a mapping table. 我想将myparam与映射表进行比较。 If the param name is a phone company, I want to delegate to /phones . 如果param名称是电话公司,我想委托给/phones If it's a car company, I want to delegate to /cars , etc. You get the idea. 如果它是一家汽车公司,我想委托/cars等。你明白了。

Also I have to rewrite the url as follows: localhost/myapp/phones?myparam=Nokia . 另外我必须重写网址如下: localhost/myapp/phones?myparam=Nokia Thereby the ngRoute would automatically catch the correct template and controller. 因此,ngRoute将自动捕获正确的模板和控制器。

Question: how can I intercept the initial loading, and redirect based on the url param? 问题:如何拦截初始加载,并根据url param重定向?

Sidenote: I cannot rewrite the routeProvider config eg by using a different plugin like angular-ui-router . 旁注:我无法重写routeProvider配置,例如使用不同的插件,如angular-ui-router

It sounds like you might want to take a step back and reconsider why you're trying to tackle it this way but given your constraints, your best bet may be to have a service that returns the correct URL and call it from the controller: 听起来你可能想退后一步并重新考虑为什么你试图以这种方式解决它,但考虑到你的限制,你最好的选择可能是有一个服务返回正确的URL并从控制器调用它:

phonecatApp.controller("trafficCtrl", function ($routeParams,trafficService,$location) {
    if ($routeParams.myparam) {
        var destination = trafficService.getDestination($routeParams.myparam);
        $location.path(destination);
    }
})
.service("trafficService", function () {
    this.getDestination = function (paramValue) {
        switch(paramValue) {
            case "Nokia":
                return "/phones";
            case "Ford":
                return "some/car/url";
            // etc...
        }
    }
});

Also, you have to add the following (generic) route to the provider: 此外,您必须将以下(通用)路由添加到提供程序:

$routeProvider.when("/", {
      template: '',
      controller: 'trafficController'
});

我不知道这是否是正确的解决方案..但你可以创建一个新的路由/myapp ..编写一个控制器并使用$location服务重定向..使用$location.query()找到查询参数值并重定向它于是

If we make it a REST call like /my-app/Nokia or my-app/Samsung instead of Query params, I think we can dynamically route it in the config itself. 如果我们将它调用为/ my-app / Nokiamy-app / Samsung而不是Query params,我认为我们可以在配置本身中动态路由它。

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/my-app/:myparam', {
        templateUrl: function(params){
         return TemplateMappingFunction(params.myparam) +'.html'
    },
        controller: function(params){
         return ControllerMappingFunction(params.myparam)
    }
      })

    //many more routes
  }]);

For example, 例如,

  • if the URL is /my-app/Nokia , TemplateMappingFunction(Nokia) will return partials/phone-list.html', 如果URL是/ my-app / Nokia ,TemplateMappingFunction(Nokia)将返回partials / phone-list.html',
  • if the URL is /my-app/Nokia , TemplateMappingFunction(Nokia) will return partials/phone-list.html', 如果URL是/ my-app / Nokia ,TemplateMappingFunction(Nokia)将返回partials / phone-list.html',
  • if the URL is /my-app/BMW , TemplateMappingFunction(BMW) will return partials/car-details.html', 如果网址为/ my-app / BMW ,则TemplateMappingFunction(BMW)将返回partials / car-details.html',

Query Param approach 查询参数方法

 phonecatApp.config(['$routeProvider',
          function($routeProvider) {
           /* Function to retrieve Query parameters*/
           function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                    results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            }

            $routeProvider.
              when('/my-app', {
                templateUrl: TemplateMappingFunction(getParameterByName('myparam'))
            },
                controller: ControllerMappingFunction(getParameterByName('myparam'))
            }
              })

            //many more routes
          }]);

So, if the URL is localhost/my-app?myparam=Nokia , then TemplateMappingFunction('Nokia') will return 'partials/phone-list.html' 因此,如果URL是localhost / my-app?myparam = Nokia ,那么TemplateMappingFunction('Nokia')将返回'partials / phone-list.html'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM