如何编写通用标题&使用ui路由器状态的Angularjs中的页脚

时间:2015-10-07 10:50:42

标签: javascript jquery html css angularjs

我正在使用ui路由器状态。我有两个不同的控制器,将来也可以扩展。如何编写默认和通用标题&页脚。

var myApp = angular.module('myApp', ['ui.router']);

myApp.controller('MainCtrl', function($scope) {});

myApp.config(function($stateProvider, $urlRouterProvider) {

    // default route
    $urlRouterProvider.otherwise("/first");

    // ui router states
    $stateProvider
        .state('first', {
            url: "/first",
            views: {
                header: {
                    template: '<h1>First header</h1>',
                    controller: function($scope) {}
                },
                content: {
                    template: '<p>First content</>',
                    controller: function($scope) {}
                },
                footer: {
                    template: '<div>First footer</div>',
                    controller: function($scope) {}
                }
            }
        })
        .state('second', {
            url: "/second",
            views: {
                header: {
                    template: '<h1>Second header</h1>',
                    controller: function($scope) {}
                },
                content: {
                    template: '<p>Second content</>',
                    controller: function($scope) {}
                },
                footer: {
                    template: '<div>Second footer</div>',
                    controller: function($scope) {}
                }
            }
        });

});

Jsfiddle:http://jsfiddle.net/karthikreddy/b7cnszdf/

2 个答案:

答案 0 :(得分:3)

请参阅此演示:http://jsfiddle.net/tkf954a5/

您可以将页脚和标题定义为:

  var header = {
       template: '<h1>Im Header</h1>',
       controller: function($scope) {}

  }

然后在你的州使用它:

 .state('first', {
            url: "/first",
            views: {
                header: header,
                content: {
                    template: '<p>First content</>',
                    controller: function($scope) {}
                },
                footer: footer
            }
        })

答案 1 :(得分:0)

我建议你将你的视图(html)和控制器代码放在不同的文件中,以使事情更具可读性。

Ui-router允许您创建嵌套状态。有了它,你可以创建一个具有页眉和页脚的基本状态,然后将所有yout状态添加为嵌套状态。

有关详情,请参阅:https://github.com/angular-ui/ui-router/wiki/Nested-States-and-Nested-Views

它看起来像这样:

.state('base',{
    url: '',
    views: {
        'header': {
             controller: 'HeaderCtrl',
             templateUrl: 'views/header.html'
        },
        'main': {
            template: '<ui-view/>'
        },
        'footer': {
            controller: 'FooterCtrl',
            templateUrl: 'views/footer.html'
        }
    }
})

.state('base.first', {
    url: '/first',
    controller: 'FirstCtrl',
    templateUrl: 'first.html'
})

.state('base.first', {
    url: '/second',
    controller: 'SecondCtrl',
    templateUrl: 'second.html'
})

修改

如果您不想使用嵌套状态,可以将视图和控制器放在单独的文件中,并将它们包含在您创建的每个路径中。它不是将整个代码放在那里,而只是一个字符串。

相关问题