简体   繁体   中英

AngularJS $stateProvider loads parent but not child template

I just started migrating to AngularJS and I'm already having problems with the $stateProvider from the angular-ui/ui-router framework. This is what I have so far:

angular
    .module('testApp', ['ui.router'])
    .config(function($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/index/home");

        $stateProvider
            .state('index', {
                abstract: true,
                url: "/index",
                template: "parent"
            })
            .state('index.home', {
                url: "/home",
                template: "child"
            })
    })
    .controller("MainController", function() {
    })

Now, running this script redirects me to http://example.com/#/index/home but it only displays the parent string on the page. The child string is not being shown. From my understanding this should load the first template because we are on the /#/index domain part and then the second because we are on a nested page /#/index/home .

Can someone help me and explain why this is not working as intended?

In your template for the parent you need another <div ui-view></div> in order to render child states.

If you want multiple nested views, you can have multiple ui-view in your parent template. You just have to name them. For example,

parent template:

<h1>parent</h1>
<div ui-view="child1"></div>
<div ui-view="child2"></div>

And you define the child states as follows:

$stateProvider
        .state('index', {
            abstract: true,
            url: "/index",
            template: "parent"
        })
        .state('index.home', {
            url: "/home",
            views: {
             'child1': {
               templateURL: "child1.html"
              }
            }
        })
        .state('index.home2', {
          url: '/home2',
          views: {
           'child2': {
             templateURL: 'child2.html'
          }
          }
        })

*note I used templateURL instead of template. Assuming your app has modular file structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM