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

标签 angularjs angularjs-ng-include

我打算在具有不同 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/

相关文章:

javascript - Angularjs data-ng-include 不起作用

javascript - 如何使用具有自定义属性的 Angular js ngOptions

javascript - 如何在 AngularJS 中通过 AJAX 添加 ngmodel

javascript - AngularJS,UI Bootstrap DropDown Toggle,如果绑定(bind)了参数,则 ng-click 不会触发

angularjs/渲染 内联或使用 ng-include 之间的性能差异

angularjs - Chrome 应用程序(沙盒)与 AngularJS

javascript - Angularjs 默认表单错误消息样式/css

javascript - 在 Ionic Framework (AngularJS) 中保存应用程序设置

javascript - 在其他域的 div 中包含一个 Angular 应用程序,没有 iframe

javascript - 使用 ng-include 时失去作用域