Angular ui-router dynamically create template usin

2019-09-01 05:15发布

Hi I'm trying to dynamically create templates based on the uri eg, contacts/jane would use the template contacts.jane.html

contacts.js

'use-strict';

angular.module('meanApp')
.config(function ($stateProvider) {
  $stateProvider
    .state('contacts', {
        url: '/contacts',
        controller: 'ContactsCtrl',
        views: {
            '': {
                templateUrl: 'app/contacts/contacts.html'
            },
            'list@contacts': {
                templateUrl: 'app/contacts/contacts.list.html'

            },
            'details@contacts': {
                templateUrl: function ($stateParams) {
                   return 'app/contacts/' + $stateParams.id + '.html';
                },
                controller: function ($scope, $stateParams) {

                }
            }
        }
    })
    .state('contacts.details', {
        url: '/:id',
        controller: 'ContactsCtrl'
    });
  });

contacts.html

<div ng-controller="ContactsCtrl">
<h1>My Contacts</h1>
<div ui-view="details"></div>
<div ui-view="list"></div>

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-01 05:46

There is a working example. What we need here, is to define the template inside of the child state:

  $stateProvider
    .state('contacts', {
      url: '/contacts',
      controller: 'ContactsCtrl',
      views: {
        '': {
          templateUrl: 'app/contacts/contacts.html'
        },
        'list@contacts': {
          templateUrl: 'app/contacts/contacts.list.html'

        },
        'details@contacts': {
          // this could be, filled on a contacts state
          // with some default content
          template: "place for detail",
        }
      }
    })
    // this state has the 'id' defined
    // so, here we can decide which template to use
    // based on the $stateParams
    .state('contacts.details', {
      url: '/:id',
      views: {
        "details": {
          controller: 'ContactsCtrl',
          templateUrl: function($stateParams) {
            url = 'app/contacts/' + $stateParams.id + '.html'
            return url;
          },
        }
      }
    });

Also, the controller is defined in state so the template contacts should/could for example look like this (no ng-controller):

<div>
 <h1>My Contacts</h1>
 <div ui-view="list"></div>

 <hr />
 <div ui-view="details"></div>
</div>

Check that in action here

查看更多
登录 后发表回答