angular.js - angularjs公共头部的headController控制器如何获取路由配置中的参数?

【字号: 日期:2023-01-14浏览:26作者:雯心

问题描述

举个例子:应用中有三个控制器,它们是平级的关系A控制器控制页面的head部分B和C控制器控制详情页面和编辑页面,路由关系如下

when(’/detail/:id’, { templateUrl: ’tpls/detail.html’, controller: 'BController' }).when(’/edit/:id’, { templateUrl: ’tpls/edit.html’, controller: 'CController' }).

现在的需求是在A控制器中要获取路由URL中的参数id,该如何获取?

我当前的实现方式:我写了一个service,在service中写一个函数,这个函数的的作用就是用$location.path()的方式拿到当前URL,然后再使用字符串截取的方式取到参数中的id,虽然拿到了值,但是感觉不应该是这个方式

我的尝试:

$location有一个API,$location.search().name 是用来获取当前url参数的,但是这个api无法获取我的参数,因为我的url里是形如 index.html#/detail/1 的形式,没有name无法获取

还有一个想法是在三个控制器上再加一个更高级的控制器,通过父控制器中转,但是这样似乎也不妥

问题解答

回答1:

你就不能把id放到cookies里面么

回答2:

angular-ui 专用获取$stateParams

回答3:

注入$route然后$route.current.params就是

回答4:

http://stackoverflow.com/questions/25370775/exposing-the-current-state-name-with-ui-router

//this watches for state changes$rootScope.$on(’$stateChangeStart’, function(event, toState, toParams, fromState, fromParams){ //do something when state changes $yourService.state = toState.name; $yourService.postid = toParams.postid; console.log(toParams); //this is the stateParams you need});回答5:

把这个服务注入$routeParams,然后

$scope.id = $routeParams.id

相关文章: