技术控

    今日:118| 主题:49179
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Advanced Angular 1.x: Component Communication with Require

[复制链接]
qijiworld20140 发表于 3 天前
86 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Angular 1.5’s components have made scope isolation the default, and rightly so. But, it does mean that inter-component communication requires more thought to get right.
  Angular’s    requiremechanism provides a good way to allow some forms of components communication, especially across a suite of related components.  
    What does      requirelet you do?   
    When should you use it?
    Why it’s not the right tool for everything?
    Keep reading!
    How require works?

  The require mechanism is an old one, and has been in use quite a lot for advanced Angular directive communication.
  Prior to components, you’d use    requirein order to allow a directive access to a different directive’s controller. That allows directives to expose APIs between one another.  
  A directive can require the existence of another specific directive, either on its own element or on one of its parent elements.
  An example of a same-element kind of communication require is used for, is adding your own validation directive to an    inputelement, and accessing that input’s    ngModelControllerin order to modify the validators.  
  Accessing parent controllers is more useful for suites of interacting components, such as the way Angular’s form validation works. Every input element in the form can notify the form that it has become valid, invalid, dirty, etc. by optionally requiring a parent    ngFormcontroller and updating it of changes.  
  As you can see, require is a very powerful mechanism and an inherent part of Angular, that you can use to make your own components cleaner.
  When should or shouldn’t you use require?

  First and foremost, require doesn’t work in all scenarios. It can only be used by a component/directive to get access to a parent controller (or a controller on the same element). Sibling components can’t communicate using it, and neither can a parent component access its children using it (at least not directly, keep reading for an interesting option).
  Another limitation of require is that it assumes the child component knows the name of the other component that it want to require. There’s no abstraction/indirection here – the name of the required component is hard-coded in the requiring component.
  Also, I wouldn’t rush to use require to replace any kind of simple binding. It’s totally fine to pass some values between components using bindings–it can be more explicit and simpler to maintain. After all, it’s usually easier to understand what a component depends on if all you need to do is look at its bindings.
  Require shines when it allows you setup a family of interacting components, and exposing a rich interface between them without having to wire up half a dozen bindings across multiple layers of components.
  Real require example deep-dive: Angular’s forms

  As already mentioned, Angular’s whole form and validations mechanism makes heavy use of require.
  When you create a    <form>in Angular, every element inside it that uses    ng-model, such as    <input>s,    <select>s, etc. registers itself as a control inside that form.  
  You can see    herein the source of    ngModelhow it optionally requires the    formdirective. In case a parent form directive exists,    ngModelControlleruses the form directive’s controller and registers as a control. See    here.  
  The form directive, in turn, keeps a list of all these controls and updates them on changes such as    $setPristineand    $setUntouched.  
  Notice that while there’s no direct way to access a child component from a parent component, the Angular core team did it here by using    requirefrom the child and registering it in the parent, exposing the child controllers to the parent.  
  Angular’s forms, in turn, have the ability to be nested inside other forms. This happens by    optionally requiring a parent formcontroller. If    requiredoes find another parent form directive, the nested form registers in it to let the parent form know it has nested forms.  
  This is an excellent example of setting up a component architecture, where our components know about one another and use that knowledge to their advantage.
  Real talk: How do you use require in your components

  Let’s say that we’ve got this structure in our application:
           
  1. <parent>
  2.   <child></child>
  3. </parent>
复制代码
       And we want to allow the    childcomponent to access    parentcomponent’s controller.  
  We’ll add a    requireblock in    child’s component definition, and then be able to access the controller inside the controller, like so:  
           
  1. app.component('child', {
  2.   require: {
  3.     parentCtrl: '^^parent'
  4.   },
  5.   controller: function() {
  6.     var self = this;
  7.     this.$onInit = function() {
  8.       self.parentCtrl.someControllerFunc();
  9.     };
  10.   }
  11. });
复制代码
       What do we have here? The    requireobject allows us to pass as many required component as we’d like.    parentCtrlis the name the required controller will be bound as in our component’s controller.    ^^parentmight seem live a bit of voodoo, but basically we’re saying that we require a parent component called    parentto exist.  
  The    ^^prefix means the component has to be a parent. There’s also the    ^, which means we can use a component that’s either a parent or on the current element. And if you simply provide the name, e.g.    fooCtrl: 'foo'it means you expect the    foodirective to exist on the current element–it will not be searched for anywhere else.  
  When we’re talking about components, and not directives, you almost always want    ^^, though you can use just    ^if you don’t    reallywant to make sure you’re not accidentally requiring the current element.  
  After we require a component, we can access it from our controller with the name we provided, e.g.    this.parentCtrl. I prefer to make sure the name still uses the original component’s name, to be explicit and make maintenance easier.  
  If the require string is written like we saw above, it means the component is strictly required. Angular will error out if it can’t find the component we asked for. In cases where a component can operate without that required component, you can set the requirement as optional:
           
  1. require: {
  2.   parentCtrl: '?^^parent'
  3. }
复制代码
       The question mark means that in case Angular can’t find a parent component with that name it will silently ignore it. If you’ll try to access    this.parentCtrlyou’ll see it’s just nulled.  
  With great require comes great responsibility

  Require is an advanced Angular technique that can really boost certain parts of your app. It’s great for exactly those few highly-interactive components you need to write.
  But,    requiresurely shouldn’t be your default or go-to solution for all communication. Start by using regularone-way (    <) andexpression (    &) bindings, and reach for    requirewhen it’s required (pun slightly intended).  
    You want to do Angular      the right way.   
    You hate spending time working on a project, only to find it’s completely wrong a month later.
    But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
    Every line of code you write means making decisions, and it’s paralyzing.
      You look at blog posts, tutorials, videos, but each is a bit different.
    Now you need to      reverse engineer every adviceto see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.   
      What if you knew the      Angular Wayof doing things?   
    Imagine knocking down your tasks and spending your brain cycles on your product’s core.
    Wouldn’t it be nice to know Angular like a second language?
      You can write modern, clean and future-ready Angular right now.
    Sign up below and get more of these helpful posts, free!
    Always up to date and I’ve already done all the research for you.
    And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.
友荐云推荐




上一篇:Swap Nodes in Binary tree of every k’th level
下一篇:Redis + Node.js: Introduction to Caching
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表