Angular UI Router:访问ui-view外的状态参数

时间:2015-08-21 14:24:25

标签: angularjs controller angular-ui-router

菜单位于<div>块之外,通过UI路由器的ui-view呈现。

为了根据状态参数修改菜单,我需要从菜单控制器中访问当前状态参数,但$stateParams变量在ui-view之外使用时是一个空对象一部分。

我如何访问它们?

angular.module('myapp').controller('MenuCtrl', ['$scope', '$rootScope', '$stateParams', '$meteor', '$filter',
  function($scope, $rootScope, $stateParams, $meteor, $filter) {
    // ... $stateParams equals {}
  }
]);

2 个答案:

答案 0 :(得分:4)

尝试监视控制器中的状态更改...

angular.module('myapp').controller('MenuCtrl', ['$scope', '$rootScope', '$meteor', '$filter',
    function($scope, $rootScope, $meteor, $filter) {

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

     }
]);

答案 1 :(得分:0)

确保将$stateParams注入控制器?你能提供你已经拥有的代码片段吗?