如何根据AngularJS中的作用域重定向到不同的模板?

时间:2022-09-22 20:58:10

I would like to have a different template based on my scope.

我希望根据我的范围有一个不同的模板。

Currently, I have only one template named : view-project.html accessible by this url : #/project/:id.

目前,我只有一个模板名为view-project。可以通过这个url访问的html: #/project/:id。

Now, I need two templates : view-project-1.html and view-project-2.html. and I need them to keep the same url : #/project/:id

现在,我需要两个模板:view-project-1。html和视图-项目- 2. - html。我需要他们保持相同的url: #/project/:id

So for example, if my $scope.template = 1, I would like to use view-project-1.html with this url #/project/300. And if $scope.template = 2 I would like to use view-project-2.html with this url #/project/300

例如,如果我的$作用域。template = 1,我想使用view-project-1。使用这个url #/project/300的html。如果美元范围。模板= 2我想使用视图-项目-2。使用这个url #/project/300的html

Is it possible to do that ?

有可能吗?

2 个解决方案

#1


2  

app.config(function($routeProvider) {
    $routeProvider
        .when('/project/:id', {
            templateUrl: 'template.html',
            controller: 'projectcontroller'
        })
});

Then in your controller:

然后在你的控制器:

app.controller('projectcontroller', function($scope) {
    $scope.template = 2;
});

template.html:

template.html:

<div ng-include="template==2?'view-project-2.html':'view-project-1.html'"></div>

DEMO PLUNKER

演示一美元

#2


1  

This, according to me, can be done in the following way :

在我看来,这可以通过以下方式来实现:

  1. Use ng-include to import both of your templates in the same file.

    使用ng-include将两个模板导入到同一个文件中。

  2. You can use ng-switch or ng-if to render one of the two templates based on the values in the route parameters.

    您可以使用ng-switch或ng-if根据路由参数中的值呈现两个模板中的一个。

#1


2  

app.config(function($routeProvider) {
    $routeProvider
        .when('/project/:id', {
            templateUrl: 'template.html',
            controller: 'projectcontroller'
        })
});

Then in your controller:

然后在你的控制器:

app.controller('projectcontroller', function($scope) {
    $scope.template = 2;
});

template.html:

template.html:

<div ng-include="template==2?'view-project-2.html':'view-project-1.html'"></div>

DEMO PLUNKER

演示一美元

#2


1  

This, according to me, can be done in the following way :

在我看来,这可以通过以下方式来实现:

  1. Use ng-include to import both of your templates in the same file.

    使用ng-include将两个模板导入到同一个文件中。

  2. You can use ng-switch or ng-if to render one of the two templates based on the values in the route parameters.

    您可以使用ng-switch或ng-if根据路由参数中的值呈现两个模板中的一个。