【问题标题】:Routing based on country基于国家的路由
【发布时间】:2018-01-17 06:41:52
【问题描述】:

我正在尝试根据国家/地区显示独特的页面。我指的是耐克网站。 https://www.nike.com/sg/en_gb/。在这里,用户可以选择地区/国家:

如何使用路由参数而不是路径来实现。我想使用路由参数或更好的解决方案来实现。

查看

<body ng-controller="CountryController">
    <form>
      <select name="naver" id="naver" ng-model="route.selectedRoute" ng-change="RedirecttoCountry(route.selectedRoute)">
        <option value="/" >Home</option>
        <option value="/US">US</option>
        <option value="/UK">UK</option>
        <option value="/India">India</option>
      </select>
    </form>
    <div ng-view=""></div>

每个国家/地区都有单独的 html。

控制器

var app = angular.module("myApp", ['ngRoute']);

app.config(function($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: "US.html",
            controller: 'CountryController'
        })
        .when('/UK', {
            templateUrl: "UK.html",
            controller: 'CountryController'
        })
        .when('/India', {
            templateUrl: "India.html",
            controller: 'CountryController'
        })
        .otherwise({ redirectTo: '/' });
});

app.controller('CountryController', function($scope, $location){
    $scope.RedirecttoCountry = function( path ){
        $location.path(path);
    }
});

【问题讨论】:

  • 如果我是正确的,你可以通过/:country添加一个参数

标签: javascript angularjs routing angularjs-routing


【解决方案1】:

您的代码似乎运行良好。只需确保您已包含所有依赖项并正确关闭所有 HTML 标记。

var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: "main.html",
        controller: 'CountryController'
    }).when('/:country', {
        templateUrl: function(params) {
            return (params.country) + '.html';
        },
        controller: 'CountryController'
    }).otherwise({
        redirectTo: '/'
    });
});
app.controller('CountryController', function($scope, $location) {
    $scope.RedirecttoCountry = function(path) {
        $location.path(path);
    }
});

使用参数的工作 Plunkerhttps://plnkr.co/edit/hFLCyGgo91GwQhpagvAz?p=preview

【讨论】:

  • 链接没有更新我相信,我没有看到参数
【解决方案2】:

templateUrl可以是参数的函数,例如:

$routeProvider
  .when('/:country', {
    templateUrl: function(params) {
      return params.country + '.html';
    }
  })
  .when('/', {
    template: 'default'
  })
  .otherwise({ redirectTo: '/' });

见: https://plnkr.co/edit/rNQutPGZ5b4B0NK5g4Wz?p=preview

【讨论】:

    【解决方案3】:

    我希望您需要动态处理所有国家/地区的单一路线,因为您可以使用templateUrl 作为函数,并将:country 定义为参数。

    .when('/:country', {
        templateUrl: function(params){
            return (params.country || 'US')+'.html';
        },
        controller: 'CountryController'
    })
    

    【讨论】:

      猜你喜欢
      • 2016-12-14
      • 2012-10-14
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多