gpt4 book ai didi

angularjs - 将 ngInclude 与 ControllerAs 语法结合使用的最佳实践是什么?

转载 作者:行者123 更新时间:2023-12-04 20:40:54 24 4
gpt4 key购买 nike

我打算在具有不同 Controller 的多个 View 中使用一个模板。

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

ngInclude 的 Angular 文档比如说

This directive creates new scope.



我可以使用 ng-init指令并将 Controller 实例传递给模板的范围:
<ng-include src="..." ng-init="controller=concreteControllerName"/> 

甚至更好
<ng-include src="..." ng-init="model=getModelForTemplate()"/>

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

我猜这是一个可行的解决方案。

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

最佳答案

使用约翰爸爸的 controllerAs View SyntaxcontrollerAs with vm .您在 ng-include 中指定不同的 Controller 指令,但使用相同的 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>

这是一个完整的工作版本:Full Working Code in Plunker

关于angularjs - 将 ngInclude 与 ControllerAs 语法结合使用的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26427950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com