简体   繁体   English

具有不同网址的Angular.js动态模板

[英]Angular.js dynamic template with different url

I am trying to build a page with a static header and footer layout, but using ng-view or ng-include to change my container template based on the URL. 我正在尝试构建具有静态页眉和页脚布局的页面,但是使用ng-view或ng-include来基于URL更改容器模板。 I've tried two methods: 我尝试了两种方法:

Using $routeProvider: 使用$ routeProvider:

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/', {
        template: 'views/home.html',
        controller: 'Ctrl',
    });
    $routeProvider.when('/contact-us', {
        template: 'views/contact.html',
        controller: 'Ctrl',
    });
    $routeProvider.otherwise({
        redirectTo: '/'
    });

}]);

or a controller function to return a template URL: 或控制器函数以返回模板URL:

app.controller('locationCtrl', function ($scope, $location, $routeParams) {
    $scope.templateUrl = function() {
        return "/views/home.html";

    }
});

However, with either one I get am unable to get a contact-us error message. 但是,无论使用哪种方法,我都无法获得与我们联系的错误消息。

routerProvider runs before all of controllers. routerProvider在所有控制器之前运行。 So you can't simply change templateUrls dynamically. 因此,您不能简单地动态更改templateUrls。 But you can use ng-include conditionally: 但是您可以有条件地使用ng-include

<div ng-controller="SubPageCtrl>
    <ng-include src="templateUrl"></ng-include>
</div>
<script>
function SubPageCtrl($scope) {
    if ( something ) {
         $scope.templateUrl = '/some.html';
    } else {
         $scope.templateUrl = '/other.html';
    }
}
</script>
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
    template: 'views/home.html',
    controller: 'Ctrl',
});
$routeProvider.when('/contact-us', {
    template: 'views/contact.html',
    controller: 'Ctrl', // Controller should be different
});
$routeProvider.otherwise({
    redirectTo: '/'
});
}]);

Replace To : 替换为:

 app.config(['$routeProvider', function ($routeProvider) 
$routeProvider.when('/', {
    templateUrl: 'views/home.html', //template should be templateUrl
    controller: 'Ctrl',
});
$routeProvider.when('/contact-us', {
    templateUrl: 'views/contact.html', //template should be templateUrl
    controller: 'Ctrl',
});
$routeProvider.otherwise({
    redirectTo: '/'
});
}]);

Your 1st method will work. 您的第一种方法将起作用。

You should define your routes from more specific urls to more general urls. 您应该定义从更具体的URL到更一般的URL的路由。 Because routes match with urls that start with your definition. 因为路由与以您的定义开头的网址匹配。

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/contact-us', {
        template: 'views/contact.html',
        controller: 'Ctrl',
    });
    $routeProvider.when('/', {
        template: 'views/home.html',
        controller: 'Ctrl',
    });
    $routeProvider.otherwise({
        redirectTo: '/'
    });

}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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