我正在尝试构建一个具有静态页眉和页脚布局的页面,但使用 ng-view 或 ng-include 根据 URL 更改我的容器模板。我尝试过两种方法:
使用$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: '/'
});
}]);
或返回模板 URL 的 Controller 函数:
app.controller('locationCtrl', function ($scope, $location, $routeParams) {
$scope.templateUrl = function() {
return "/views/home.html";
}
});
但是,无论是哪一个,我都无法收到联系我们错误消息。
最佳答案
routerProvider 在所有 Controller 之前运行。所以你不能简单地动态改变 templateUrls 。但你可以使用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>
关于javascript - 具有不同 url 的 Angular.js 动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18881014/