Angular ui-router使用$ stateParams和嵌套模板动态创建模板,错误,$ stateParams未定义

时间:2015-02-01 18:31:48

标签: angularjs angular-ui-router

您好我试图根据uri动态创建模板,例如,contacts / jane会使用模板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 个答案:

答案 0 :(得分:0)

a working example。我们在这里需要的是定义状态内的模板:

  $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;
          },
        }
      }
    });

此外,controller是在状态中定义的,因此模板联系人应该/可能看起来像这样(无ng-controller)

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

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

检查行动here