2017-04-06 42 views
0

我正在嘗試管理列表和列表元素的CRUD。ui-router父母狀態可選參數

我想有一個狀態,一個模板和一個控制器每個元素(創建/編輯)。

我創作的狀態:

state('list', { 
       parent: 'root', 
       url: '/list?list_id', 
       views: { 
        '[email protected]': { 
         templateUrl: 'list.tmpl.html', 
         controller: 'ListController', 
         controllerAs: 'vm', 
        } 
       } 
      }) 

這是完美的,在控制器我可以檢查一個LIST_ID和切換betweend創建/編輯。

當上述狀態變爲父項時會出現此問題。 當孩子介紹:

state('list-element', { 
       parent: 'list', 
       url: '/element?list_id&element_id', 
       views: { 
        '[email protected]': { 
         templateUrl: 'element.tmpl.html', 
         controller: 'ElementController', 
         controllerAs: 'vm', 
        } 
       } 
      }) 

我也不再有我需要的不確定性。 ?

說得更簡單,我想要的網址結構是這樣的:?

  • /列表LIST_ID - 如果LIST_ID切換編輯
  • /列表/元LIST_ID & element_id - 如果element_id切換編輯

請注意,當創建list元素時,父狀態沒有參數。現在

,我可以解決此通過的名單產生兩種狀態:

  1. /表(母公司)創建
  2. LIST_ID(子1)編輯
  3. /element?list_id & element_id(child for 1)創建或編輯

但這會打破我想要的「一個狀態,一個模板和一個控制器」。

無論如何,我可以做到這一點我想要的方式

回答

0

我知道你正在尋找一個特定的實現,但我認爲你遇到麻煩的部分原因是因爲這種方法可能不是你想要做的最好的,因爲它看起來像你混淆了路線與DOM元素的作用。

組件(和指令)旨在幫助您顯式地將控制器和模板捆綁在頁面上的元素上。路由正是讓你在那裏,並告訴你加載哪些。這裏是你會如何使用更傳統的方法處理這個問題:

stateHelperProvider.state({ 
    name: 'list', 
    url: '/list' 
    // This is possible with https://github.com/marklagendijk/ui-router.stateHelper 
    children: { 
    name: 'element', 
    // Example: /list/123 
    url: '/{list_id:int}?element_id', 
    resolve: { 
     item: ['$stateParams', 'FooService', ($stateParams, FooService) => { 
     // Get whatever info you need, based on the ID. 
     return FooService.getItem($stateParams.list_id); 
     } 
    }, 
    views: { 
     '[email protected]': { 
     // This will use the resolved `item` and pass it into the component. 
     template: '<list-element item="$resolve.item"></list-element>' 
     } 
    } 
    } 
}); 

// The component 
(function() { 
    'use strict'; 
    angular.module('yourModule') 
    .component('listElement', { 
     templateUrl: 'element.tmpl.html', 
     bindings: { 
     item: '<' 
     } 
    }); 
})(); 

// Sample component template 
<h2 ng-bind="$ctrl.item.name"></h2> 
<div ng-bind="$ctrl.item.description"></div> 

對於不同的路線,你可能想看看nested named views in UI Router。這將允許您分別指定不同的控制器,模板和狀態。要點:

<!-- Parent template --> 
<div ui-view="editContents"></div> 
<div ui-view="previewContents"></div> 
+0

我已經用另一種方式解決了這個問題:我將'/ list'狀態作爲根,默認子狀態爲'?list_id'。從那裏,我實現了'?list_id'和'/ element?list_id&element_id'作爲孩子到'/ list',這對我來說工作得很好。對我而言,你看起來過於複雜了。感謝您的時間! – alexpopa