2016-09-09 18 views
3

我想參數傳遞到嵌套的UI視圖:參數傳遞到用戶界面視圖

<ui-view user="user"></ui-view> 

現在讓我解釋爲什麼我需要這個。 這就是我的UI看起來像:

enter image description here

它的用戶卡的角度成分。在這個組件內部有幾個標籤,像子組件和自己的狀態。我的目標是爲來自父狀態的選項卡提供用戶對象。

讓我也表現出一定的簡化代碼:

.state('user', { 
    url: '/user/:userId', 
    template: `<user user-id="userId"></user>`, 
    controller: ($scope, $stateParams) => { 
     $scope.userId = +$stateParams.userId; 
    } 
    }) 
    ... 
    .state('user.tab1', { 
    url: '/tab1', 
    template: '<tab1 user="$ctrl.user"></tab1>', 
    controller: ($scope, $state) => { 
     //I would like to get access to the user object here 
     let course = $scope.$ctrl.user; 
    } 
    }); 

所以更多的時間:用戶對象是在UI路由器控制器裝不會,但組件的控制器。這個組件的模板嵌套在我想要的用戶對象中。

+0

Ui路由器未更新爲遵循角度1.5的組件。所以,這是錯過了。您可以使用$ scope(而不是$ scope。$ ctrl)或類似的解決方法來傳遞對象。 –

回答

2

我發現UI路由器不會產生孤立的範圍爲孩子指出, 這樣你就可以通過

$scope.$ctrl.youparentproperty 

方便地訪問他們,在我的情況是:

.state('user.tab1', { 
    url: '/tab1', 
    template: '<tab1 user="$ctrl.user"></tab1>', 
}); 

和例如,如果別人正在努力解決同一問題 - https://plnkr.co/edit/9LSNtWWcom6ERZRBucXB?p=preview

0

您可以通過父級屬性指定一個州的父級。

.state('user', { 
     url: '/user/:userId', 
     template: `<user user-id="userId"></user>`, 
     controller: ($scope, $stateParams) => { 
      $scope.userId = +$stateParams.userId; 
     } 
     }) 
     ... 
     .state('user.tab1', { 
     url: '/tab1', 
     parent: 'user', 
     template: '<tab1 user="$ctrl.user"></tab1>', 
     controller: ($scope, $state) => { 
      //In order to access the scope of a parent controller in Angular UI Router use: 
      let course = $scope.$parent.user; 
     } 
     }); 

另一種解決方案可以把你的用戶變量到你可以在每個控制器訪問或放在$rootscope的服務。

+2

謝謝你的回答,但我認爲'$ scope。$ parent'和'$ rootScope'不是最佳實踐 –