Javascript Angular 1.5 组件与旧指令 - 链接函数在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33709062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:22:38  来源:igfitidea点击:

Angular 1.5 component vs. old directive - where is a link function?

javascriptangularjsangularjs-directiveangular-directive

提问by troorl

I've been reading this nice recent articleabout new .component()helper in Angular 1.5, which is supposed to help everyone to migrate to Angular 2 eventually. Everything looks nice and simple, but I couldn't find any information about DOM manipulation inside components.

我最近一直在阅读这篇关于.component()Angular 1.5 中的新助手的好文章,它应该可以帮助每个人最终迁移到 Angular 2。一切看起来都很简单,但我找不到任何关于组件内部 DOM 操作的信息。

There is a templateproperty though, which can be a function and accept $elementand $attrsarguments. Still it's not clear to me if that's the replacement for a linkfunction. It doesn't seem so.

但是有一个template属性,它可以是一个函数和接受$element$attrs参数。我仍然不清楚这是否是link功能的替代品。似乎不是这样。

回答by jody tate

EDIT 2/2/16:The 1.5 documentation now covers components: https://docs.angularjs.org/guide/component

编辑 2/2/16:1.5 文档现在涵盖组件:https: //docs.angularjs.org/guide/component



Some thoughts based on some reading (links below):

基于一些阅读的一些想法(下面的链接):

  • Components aren't replacements for directives. A component is a special type of directive that organizes a controller with a template.

  • Components do not have a link function and controllers still are not where you'd handle DOM manipulation.

  • If you need DOM manipulation, your component can use other directives that include that DOM manipulation in a link function.

  • 组件不是指令的替代品。组件是一种特殊类型的指令,它用模板组织控制器。

  • 组件没有链接功能,控制器仍然不是您处理 DOM 操作的地方。

  • 如果您需要 DOM 操作,您的组件可以使用其他指令,在链接函数中包含该 DOM 操作。

It took me a while to figure this out, but once I did it made some sense: components are directives but not all directives are--or need to be--components.

我花了一段时间才弄明白这一点,但是一旦我做了它就明白了:组件是指令,但并非所有指令都是——或需要是——组件。

The question about link functions is a natural one, or was to me, when I thought components were replacing directives. Why? Because we've been taught to put DOM manipulation inside a directive's link function: "Directives that want to modify the DOM typically use the link option to register DOM listeners as well as update the DOM." https://docs.angularjs.org/guide/directive.

关于链接函数的问题是一个很自然的问题,或者对我来说,当我认为组件正在替换指令时。为什么?因为我们被教导将 DOM 操作放在指令的链接函数中:“想要修改 DOM 的指令通常使用链接选项来注册 DOM 侦听器以及更新 DOM。” https://docs.angularjs.org/guide/directive

If you're running with that assumption (components replace directives), then you'll find that the Angular docs don't answer the question because, well, it's not the right question once you know the purpose of a component. (Components are described in the $compileProvider documentationnot the directive documentation.)

如果你在运行这个假设(组件替换指令),那么你会发现 Angular 文档没有回答这个问题,因为一旦你知道了组件的目的,这不是正确的问题。(组件在$compileProvider 文档而不是指令文档中描述。)

Background reading

背景阅读

What I say above is really a rephrasing of what Todd Motto has said in what's probably the best discussion (so far) on components and directives:

我上面所说的实际上是对 Todd Motto 在可能是(迄今为止)关于组件和指令的最佳讨论中所说的内容的重新表述:

https://www.reddit.com/r/angularjs/comments/3taxjq/angular_15_is_set_to_introduce_the_component/

https://www.reddit.com/r/angularjs/comments/3taxjq/angular_15_is_set_to_introduce_the_component/

It could be useful to have those comments pulled out into a more general article.

将这些评论提取到更一般的文章中可能会很有用。

Most articles on components don't mention a link function (this doesn't mean these aren't excellent articles):

大多数关于组件的文章都没有提到链接函数(这并不意味着这些文章不是优秀的文章):

https://toddmotto.com/exploring-the-angular-1-5-component-method/

https://toddmotto.com/exploring-the-angular-1-5-component-method/

https://medium.com/@tomastrajan/component-paradigm-cf32e94ba78b#.vrbo1xso0

https://medium.com/@tomastrajan/component-paradigm-cf32e94ba78b#.vrbo1xso0

https://www.airpair.com/angularjs/posts/component-based-angularjs-directives

https://www.airpair.com/angularjs/posts/component-based-angularjs-directives

Or when the link function is mentioned it is in parentheses:

或者当提到链接函数时,它在括号中:

http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html

http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html

One articlesays that components, "use controllers instead of link functions." But it's not an "instead" situation: controllers aren't stand-ins for link functions.

一篇文章说组件“使用控制器而不是链接功能”。但这不是“相反”的情况:控制器不是链接功能的替代品。

回答by surekha shelake

This makes it easier to write an app in a way that's similar to using Web Components or using Angular 2's style of application architecture.

这使得以类似于使用 Web Components 或使用 Angular 2 的应用程序架构风格的方式编写应用程序变得更加容易。

Advantages of Components:

组件的优点:

simpler configuration than plain directives promote sane defaults and best practices optimized for component-based architecture writing component directives will make it easier to upgrade to Angular 2

比普通指令更简单的配置促进了合理的默认值,并且针对基于组件的体系结构编写组件指令优化的最佳实践将使升级到 Angular 2 变得更容易

When not to use Components:

何时不使用组件:

for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable when you need advanced directive definition options like priority, terminal, multi-element when you want a directive that is triggered by an attribute or CSS class, rather than an element

对于依赖 DOM 操作的指令,添加事件侦听器等,因为当您需要由属性或 CSS 类触发的指令时需要高级指令定义选项(如优先级、终端、多元素)时,编译和链接功能不可用, 而不是一个元素

回答by Ekaterina Tokareva

Update (from august 22, 2017): $inject is recommended way for doing this in AngularJS. Read Styleguide: Styleguide linkand AngularJS docs: AngularJS docs

更新(从 2017 年 8 月 22 日开始):$inject 是在 AngularJS 中执行此操作的推荐方式。阅读样式指南: 样式指南链接和 AngularJS 文档:AngularJS 文档

For using DOM bindings in components instead of creating directive with link function you can inject '$element' or other service you need in your controller function, e.g.

为了在组件中使用 DOM 绑定而不是使用链接函数创建指令,您可以在控制器函数中注入“$element”或其他您需要的服务,例如

app.component('pickerField', {
    controller: PickerField,
    template: '<span>Your template goes here</span>'
  });

  PickerField.$inject = ['$element'];

  function PickerField(element) {
    var self = this;
    self.model = self.node.model;
    self.open = function() {
      console.log('smth happens here');
    };
    element.bind('click', function(e) {
      console.log('clicked from component', e);
      self.open();
    });
  }

回答by troorl

Ok, so it appears that controller is the right place for it now, since it is the only possible one. Also we can't use a replaceoption in the a component helper.

好的,现在看来控制器是适合它的地方,因为它是唯一可能的地方。我们也不能replace在组件助手中使用选项。

回答by Szymon

You can use $postLink() function which is in newest angular.

您可以使用最新角度的 $postLink() 函数。

https://docs.angularjs.org/guide/component

https://docs.angularjs.org/guide/component

Similar to the post-link function this hook can be used to set up DOM event handlers and do direct DOM manipulation.

类似于 post-link 函数,这个钩子可用于设置 DOM 事件处理程序并进行直接的 DOM 操作。

回答by barraq

According to current Angular2 documentation (see https://github.com/angular/angular/blob/master/modules/angular2/docs/core/02_directives.md) there will still be directives in Angular2. So basically you will be able to use both @Directive or @Component, where:

根据当前的 Angular2 文档(参见https://github.com/angular/angular/blob/master/modules/angular2/docs/core/02_directives.md),Angular2 中仍然会有指令。所以基本上你将能够同时使用@Directive 或@Component,其中:

  • Directives are useful for encapsulating behavior.
  • Component is a directive which uses shadow DOM to create encapsulate visual behavior. Components are typically used to create UI widgets or to break up the application into smaller components.
  • 指令对于封装行为很有用。
  • Component 是一个指令,它使用 shadow DOM 来创建封装的视觉行为。组件通常用于创建 UI 小部件或将应用程序分解为更小的组件。

So According to this, if you need DOM manipulation you will need to use @Directive, therefore Angular.directive in Angular 1.x. Event bindings can be done using the hostproperties. Concerning DOM manipulation per se there is still missing documentation (e.g. https://github.com/angular/angular/blob/master/modules/angular2/docs/core/09_compilation.mdor https://github.com/angular/angular/blob/master/modules/angular2/docs/core/08_lifecycle.md) but you can look for Lifecycleas suggested here https://stackoverflow.com/a/32062065.

所以根据this,如果您需要DOM操作,您将需要使用@Directive,因此Angular 1.x中的Angular.directive。事件绑定可以使用host属性来完成。关于 DOM 操作本身仍然缺少文档(例如https://github.com/angular/angular/blob/master/modules/angular2/docs/core/09_compilation.mdhttps://github.com/angular/ angular/blob/master/modules/angular2/docs/core/08_lifecycle.md),但您可以Lifecycle按照此处的建议进行查找https://stackoverflow.com/a/32062065

As a short answer, with Angular 1.5+, continue using angular.directiveif you have DOM access, otherwise encapsulate into angular.component. Also try to reduce as much as possible the use of $scopefor non-dom event and prefer RxJS for that see https://medium.com/front-end-developers/managing-state-in-angular-2-using-rxjs-b849d6bbd5a5#.obgb6dl6n,

简而言之,对于 Angular 1.5+,angular.directive如果您有 DOM 访问权限,请继续使用,否则将封装到angular.component. 还尝试尽可能减少$scope非 dom 事件的使用,并且更喜欢 RxJS,参见https://medium.com/front-end-developers/managing-state-in-angular-2-using-rxjs- b849d6bbd5a5#.obgb6dl6n,