了解 AngularJS 基于组件的架构方法

Understanding the AngularJS Approach to component-based architecture

最近我深入研究了一个使用 AngularJS 的项目,发现自己陷入了一个混乱的世界。我很难理解如何将 Angular 应用于我的项目。

关于我的项目的一些背景知识,我有多个部分需要在开始时加载。将其视为具有多个部分的高内容的 SPA。

在这些部分中,我试图包括 components/directives。它们可能包含父子 components/directives 或者它们可能是兄弟姐妹 components/directives。

我喜欢将它们模块化的概念,但我完全不知道如何让它们相互通信。对于亲子directives/components,我明白我可以使用includes/requires。

但是如果我有兄弟组件,例如一个预加载器和一个轮播画廊组件,我找不到任何方法让他们互相交谈。我怀疑我对方法和架构的理解是完全错误的。

请赐教,最终让我了解如何处理这种情况。

谢谢大家。

从 1.5 开始有 components。正如您在文档中看到的那样,它们应该只有 IN(由 < 绑定表示)和 OUT(&)。

当您希望两个同级组件进行通信时,您必须通过一些父组件来实现,父组件会将一个组件的 OUT 分配给另一个组件的 IN。看一个简单的例子:

angular.module('gyeong', [])
  .component('myView', {
    template: '<component-a on-some-task-finish="$ctrl.resultFromA = result"></component-a>' 
            + '<component-b priceless-result="$ctrl.resultFromA"></component-b>'
  })
  .component('componentA', {
    bindings: {
      'onSomeTaskFinish': '&'
    },
    template: '<p>This is component A. I {{ $ctrl.myData ? "have finished loading" : "am currently loading" }} the data.</p>',
    controller: function($timeout) {
      var self = this;
      $timeout(function() {
        self.myData = 'This is THE result';
        self.onSomeTaskFinish({
          result: self.myData
        });
      }, 2000);
    }
  })
  .component('componentB', {
    bindings: {
      'pricelessResult': '<'
    },
    template: '<p>This is component B. I {{ !$ctrl.pricelessResult ? "am waiting for the result" : "have received the result! It is " + $ctrl.pricelessResult }}.</p>'
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="gyeong">
  <my-view></my-view>
</div>

当然,还有其他选择(您提到的活动或服务)。但这是首选(IMO),因为它维护单一职责组件并且不公开它们的内部实现(你已经注意到我在每个 "scope" 中为相同的结果指定了不同的名称,你没注意到吗?)。