使用带有ControllerAs语法的ngInclude的最佳实践是什么?

时间:2023-02-10 20:04:25

I had the intention to use one template across several views having different controllers.

我打算在具有不同控制器的几个视图中使用一个模板。

But now I realize that I cannot just write universal binding in templates because values will be put inside $scope.concreteControllerName.

但现在我意识到我不能只在模板中编写通用绑定,因为值将放在$ scope.concreteControllerName中。

Angular docs for ngInclude say that

ngInclude的Angular文档说明了这一点

This directive creates new scope.

该指令创建新范围。

I could use ng-init directive and pass controller instance to template's scope:

我可以使用ng-init指令并将控制器实例传递给模板的范围:

<ng-include src="..." ng-init="controller=concreteControllerName"/> 

or even better

甚至更好

<ng-include src="..." ng-init="model=getModelForTemplate()"/>

and then write {{controller.boundvalue}} in template.

然后在模板中编写{{controller.boundvalue}}。

That is a working solution, I guess.

我想这是一个有效的解决方案。

And here I'd like to know whether other better approaches exist and if not, should templates always be used with some notion of passed model to abstract away from parent scope?

在这里,我想知道是否存在其他更好的方法,如果不存在,模板是否应该与传递模型的一些概念一起使用以从父范围中抽象出来?

1 个解决方案

#1


3  

Use John Papa's controllerAs View Syntax and controllerAs with vm. You specify different controllers in the ng-include directives but use the same src html template. The common vm variable name is used in the template.

使用John Papa的控制器作为视图语法和控制器与vm。您可以在ng-include指令中指定不同的控制器,但使用相同的src html模板。常用的vm变量名称用于模板中。

index.html

<div ng-include ng-controller="controllerOne as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerTwo as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerThree as vm" src="'same.html'"></div>

controllerOne.js

function controllerOne() {
    var vm = this;
    vm.name = 'Controller One!';

sharedTemplate.html

<div>{{vm.name}}</div>

Here is a full working version: Full Working Code in Plunker

这是一个完整的工作版本:Plunker中的完整工作代码

#1


3  

Use John Papa's controllerAs View Syntax and controllerAs with vm. You specify different controllers in the ng-include directives but use the same src html template. The common vm variable name is used in the template.

使用John Papa的控制器作为视图语法和控制器与vm。您可以在ng-include指令中指定不同的控制器,但使用相同的src html模板。常用的vm变量名称用于模板中。

index.html

<div ng-include ng-controller="controllerOne as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerTwo as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerThree as vm" src="'same.html'"></div>

controllerOne.js

function controllerOne() {
    var vm = this;
    vm.name = 'Controller One!';

sharedTemplate.html

<div>{{vm.name}}</div>

Here is a full working version: Full Working Code in Plunker

这是一个完整的工作版本:Plunker中的完整工作代码