如何在父视图中获取 $stateParams?

How to get $stateParams in parent view?

我想制作带有标签内容的标签。 tab-content 有它自己的视图。 这是代码示例

(function () {
    angular
        .module('infirma.konfiguracja', ['ui.router'])
        .config(routeConfig)
    ;


    routeConfig.$inject = ['$stateProvider'];
    function routeConfig($stateProvider) {
        $stateProvider
            .state('app.konfiguracja', {
                url: 'konfiguracja/',
                views: {
                    'page@app': {
                        templateUrl: 'app/konfiguracja/lista.html',
                        controller: 'konfiguracjaListaCtrl',
                        controllerAs: 'vm'
                    }
                },
                ncyBreadcrumb: {label: "Ustawienia systemu"}
            })
            .state('app.konfiguracja.dzial', {
                url: '{dzial:.*}/',
                views: {
                    'dzial@app.konfiguracja': {
                        templateUrl: 'app/konfiguracja/dzial.html',
                        controller: 'konfiguracjaDzialCtrl',
                        controllerAs: 'vm'
                    }
                },
                ncyBreadcrumb: {label: "{{vm.nazwaDzialu}}"}
            })
        ;
    }
})();

我想标记处于父状态 (app.konfiguracja) 的选定选项卡。

问题是当输入 url 时 /konfiguracja/firmy/app.konfiguracja controller

中没有 $stateParams.dzial

如何解决?

我创建了 working example for your scenario here。我想说,至少有两种方法。

第一种,一般方法,我们应该如何在 parent 视图中使用 UI-Router 及其选定的参数(标记选定的 tab/link),应该使用指令 **ui-sref-active**:

ui-sref-active="cssClassToBeUsedForSelected"

所以这可能是用法:

<a ui-sref="app.konfiguracja.dzial({dzial: item.id})" 
      ui-sref-active="selected"
      >{{item.name}}</a> 

第二种方法(我的首选)是使用参考 Model,在 parent $scope 中创建并填写child:

.controller('konfiguracjaListaCtrl', ['$scope', function ($scope, ) 
{
  $scope.Model = {};
}])

.controller('konfiguracjaDzialCtrl', ['$scope', function ($scope) 
{ 
  $scope.Model.dzial = $scope.$stateParams.dzial;
  // we should be nice guys and clean after selves
  $scope.$on("$destroy", function(){ $scope.Model.dzial = null });
}])

用法可能是这样的

<span ng-if="item.id == Model.dzial">This is selected</span>

第二种方法效果如何?检查文档:

Scope Inheritance by View Hierarchy Only

Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).

It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.

检查所有操作 here