javascript - 加载模板和创建范围时应该使用 "controllers"还是 "directives"?

标签 javascript angularjs templates angularjs-directive controllers

让我举两个例子来更好地解释我的困惑:

HTML1

<div>
    <ng-include src="template1" ng-controller="controller1">
    </ng-include>
</div>
<div>
    <ng-include src="template2" ng-controller="controller2">
    </ng-include>
</div>

HTML2

<div>
    <templateone-include src="template1">
    </templateone-include>
</div>
<div>
    <templatetwo-include src="template2">
    </templatetwo-include>
</div>

如您所见,我提供了两种加载不同模板的方法。

  1. 使用 ng-include 并分配一个 Controller 来创建范围。
  2. 使用将加载模板的指令(使用 templateUrl)并创建一个独立的范围。

我通常认为指令主要用于 DOM 操作和用于具有不同数据的不同部分的可重用代码和 Controller ,因此我会使用第一种方法而不是第二种方法,因为我们使用不同指令的唯一目的是加载不同的模板并创建一个隔离的范围。

那么您认为哪种方法更好更合适?

最佳答案

I usually think that directives are mainly used for DOM manipulations and for reusable code and controllers for different sections with different data and hence I would use 1st approach and not 2nd is because the sole purpose of us using the different directives is to load different templates and create an isolated scope.

这也是我对指令的看法。指令应该用于向某些特定的 HTML 元素添加一些行为。如果您只需要包含一个模板并将其链接到 Controller ,第一个选项绝对是可行的方法。

关于javascript - 加载模板和创建范围时应该使用 "controllers"还是 "directives"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30218953/

相关文章:

angularjs - 如何使用$ filter过滤对象数组中的特定字段('filter')

c++ - 我可以获得正式而非实际模板参数的字符串表示形式吗?

javascript - Vue.js 如何上传图像并在之后运行自定义方法

javascript - 为什么我的大部分结果都是 nan

javascript - 按键值对 Javascript 中的对象数组进行排序

javascript - AngularJS 1.4 迁移 - ngOptions : Has track by broken object equality checks?

angularjs - Angular 在工厂进行编译

javascript - css - 固定位置侧边栏导航与页脚重叠

c++ - 如何将 const 应用于 C++ 中参数列表之外的模板参数类型?

c++ - 继承和成员函数模板重载