加载模板和创建范围时应该使用 "controllers" 还是 "directives"?
Should I use "controllers" or "directives" when loading templates and creating a scope?
让我举两个例子来更好地解释我的困惑:
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>
如您所见,我提供了两种加载不同模板的方法。
- 使用 ng-include 并分配控制器来创建作用域。
- 使用将加载模板的指令(使用 templateUrl)并创建一个独立的范围。
我通常认为指令主要用于 DOM 操作以及用于具有不同数据的不同部分的可重用代码和控制器,因此我会使用第一种方法而不是第二种方法,因为我们使用的唯一目的不同的指令是加载不同的模板并创建一个独立的范围。
那么您认为哪种方法更好更合适?
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 元素添加一些行为。如果您只需要包含一个模板并将其 link 添加到控制器,第一个选项绝对是最佳选择。
让我举两个例子来更好地解释我的困惑:
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>
如您所见,我提供了两种加载不同模板的方法。
- 使用 ng-include 并分配控制器来创建作用域。
- 使用将加载模板的指令(使用 templateUrl)并创建一个独立的范围。
我通常认为指令主要用于 DOM 操作以及用于具有不同数据的不同部分的可重用代码和控制器,因此我会使用第一种方法而不是第二种方法,因为我们使用的唯一目的不同的指令是加载不同的模板并创建一个独立的范围。
那么您认为哪种方法更好更合适?
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 元素添加一些行为。如果您只需要包含一个模板并将其 link 添加到控制器,第一个选项绝对是最佳选择。