AngularJS中UI Router状态下动态视图名称的通用路由实现问询
Got it, let's work through this dynamic ui-view matching problem. The issue with your initial attempt is that Angular expressions like {{stateParams.prodType}} don't get evaluated when defining UI Router state configurations—UI Router doesn't parse template syntax there. Instead, we can leverage UI Router's support for dynamic view definitions using functions and computed property names.
Step-by-Step Implementation
Here's the cleanest approach to auto-adapt your routing to any filtersView_ModalX ui-view using stateParams.prodType:
angular.module('yourApp') .config(function($stateProvider) { $stateProvider .state('Modal.tabs', { // Include prodType in the URL to populate stateParams (or use params if you don't want it in the URL) url: '/tabs/:prodType', // Define params explicitly if you're passing prodType via state.go() instead of URL // params: { prodType: { value: null, squash: true } }, views: function($stateParams) { // Dynamically construct the view target key using prodType const dynamicViewKey = `filtersView_${$stateParams.prodType}@Modal.tabs`; // Return the views object with the dynamically generated key return { [dynamicViewKey]: { templateUrl: function(stateParams) { // Optional: Use prodType to load a matching template too return `path/to/your/templates/filters-${stateParams.prodType}.html`; }, controller: 'SharedFiltersController', // Use a shared controller for all filter views controllerAs: 'filtersVm' } }; } }); });
Key Details to Note
- Computed Property Names: We use ES6's
[dynamicViewKey]syntax to create a dynamic key in the views object—this lets us map directly to theui-view="filtersView_ModalA"orfiltersView_ModalBelements. - Views as a Function: UI Router allows the
viewsproperty to be a function that receives$stateParamsas an argument. This is where we can dynamically build our view target based on the incomingprodTypevalue. - URL vs. Hidden Params: If you don't want
prodTypevisible in the URL, define it in theparamsobject (commented out in the example) and pass it via$state.go('Modal.tabs', { prodType: 'ModalB' }). - Consistent Naming: Ensure the
prodTypevalue exactly matches the suffix in your ui-view name (e.g.,prodType: 'ModalA'maps toui-view="filtersView_ModalA"—case-sensitive!).
Why This Works
This setup eliminates the need to add a new state configuration every time you add a new filtersView_ModalX div. As long as you pass the correct prodType when navigating to Modal.tabs, UI Router will automatically target the corresponding ui-view.
内容的提问来源于stack exchange,提问作者StrugglingCoder

