如何使用ngRoute在templateUrl中使用URL参数?

时间:2014-04-09 20:37:51

标签: javascript angularjs url-routing ngroute

我正在构建一个angularjs应用程序,我的app.js看起来像这样。但是,它会引发Unknown provider: $routeParams错误。知道为什么吗?

var angularSite = angular.module('angularSite', [
  'ui.router',
  'ngRoute',
  'siteController',
  'siteDirectives'
])
.config(['$routeProvider', '$routeParams',
  function($routeProvider,$routeParams) {
    $routeProvider.
      when('/Projects', {
        templateUrl: 'partials/projects.html',
        controller: 'ProjectController'
      }).
      when('/Projects/:projectId', {
        template: 'partials/pages/'+$routeParams.projectId+'.html',
        controller: 'ProjectDetailController'
      }).
      otherwise({
        redirectTo: '/About'
      });
  }]);

3 个答案:

答案 0 :(得分:0)

$routeParams是一项服务,可以在<{1}}中 注入。

如果您想从URL参数设置您的templateUrl,正确的方法是使用函数设置modArr($('.container').find('[mod]')) function modArr(el){ var filterArray = [] // store mod , modNames = [] // store mod value , arrIndex = [] // store non duplicate index , li = [] // store modArray = el // store mod value for(var i=0; i < modArray.length; i++){ modNames.push($(modArray[i]).attr('mod')) // get mod value from div } // search for non duplicate mod value and get the index of none duplicate mod for(var i=0; i < modArray.length; i++){ if(filterArray.indexOf(modNames[i]) === -1){ filterArray.push(modNames[i]) arrIndex.push(i) // push non duplicate index value } } filterArray = [] // reset filterArray // push module from modArray to filterArray using index in arrIndex for(var i=0; i < arrIndex.length; i++){ filterArray.push(modArray[arrIndex[i]]) } // push to li array $.each(filterArray,function(i,el){ li[i] = '<li>'+ el.outerHTML +'</li>' }) $('<ul></ul>') .append(li.join('')) .appendTo('.list') } (如下所示):

.config

答案 1 :(得分:-1)

在配置级别的AngularJS 1.2访问路径参数中可用。

template: 'partials/pages/'+$routeParams.projectId+'.html',

使用:

templateUrl: function(params){ return 'partials/pages/' + params.projectId + 'html'; }

来源 - AngularJS - How to use $routeParams in generating the templateUrl?

答案 2 :(得分:-1)

在Angular模块的配置中不允许使用服务。 $ routeParams是一个服务,所以你不能在那里使用它。

我建议您通过控制器 ProjectDetailController 包含一个或另一个模板。 在此控制器中,您可以注入并使用服务 $ routeParams ,以便选择一个或另一个模板。类似的东西:

所以,你的配置:

 when('/Projects/:projectId', {
    template: 'partials/pages/main.html',
    controller: 'ProjectDetailController'
  }).

你的控制器:

Controller.$inject = ['$routeParams'];

/* @ngInject */
function Controller($routeParams) {
  var vm = this;
  vm.template = 'partials/pages/'+$routeParams.projectId+'.html';
}

您的main.html模板:

<ng-include src="vm.template"/>