何时使用控制器与指令之间的区别? [英] Difference between and when to use controllers vs directives?

查看:58
本文介绍了何时使用控制器与指令之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解控制器的用途.我知道这是您引用事物的方式,但是由于您可以将其放入指令中,因此在任何情况下,您都想在html中的特定部分使用ng-controller而不是创建具有内置控制器的指令在吗?

I'm struggling to understand what the purpose of a controller is. I understand that it is how you reference things but since you can throw it in a directive, is there ever a scenario where you would want to use ng-controller for a specific section in your html rather than creating a directive that has a controller built in?

推荐答案

是否曾经有一种情况,您想在html中的特定部分使用ng-controller而不是创建带有内置控制器的指令?

is there ever a scenario where you would want to use ng-controller for a specific section in your html rather than creating a directive that has a controller built in?

是的,绝对是.

  • 当目标是操作 DOM时,请使用指令.
  • 要创建可重复使用的 component 时,请使用指令.
  • 当您需要将值绑定到DOM时,请使用控制器.
  • Use a directive when the goal is to manipulate the DOM.
  • Use a directive when you want to create a reusable component.
  • Use a controller when all you need is to bind values to the DOM.

两种方法中的任何一种都可能有一百种,但我相信这足以证明使用一种方法优于另一种方法.

There's probably a hundred other cases that could be made for either of the two approaches, but I believe this should be enough to justify the use of one over the other.

关于两者之间的区别,请查看@yvesmancera已经指出的问题( angularjs -directives-vs-controllers ).

As for the differences between the two, look at the question that @yvesmancera already pointed you to (angularjs-directives-vs-controllers).

在Angular中,Controller是由JavaScript构造函数定义的,该函数用于扩大Angular范围.

In Angular, a Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.

当通过ng-controller指令将Controller附加到DOM时,Angular将使用指定的Controller的构造函数实例化一个新的Controller对象.将创建一个新的子作用域,并将其作为可注入参数提供给Controller的构造函数$ scope.

When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope.


从高层次上讲,伪指令是DOM元素(例如属性,元素名称,注释或CSS类)上的标记,它们告诉AngularJS的HTML编译器($ compile)将指定的行为附加到该DOM元素上,甚至进行转换DOM元素及其子元素.

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

这篇关于何时使用控制器与指令之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆