简体   繁体   中英

Understanding the AngularJS Approach to component-based architecture

Recently I dived into a project using AngularJS and found myself in a world of mess. I am having a hard time trying to understand how Angular should be applied to my project.

A little background about my project, I have multiple sections that needs to be loaded at the start. Think of it as a SPA that has a tall content with multiple sections.

In these sections, I'm trying to include components/directives. They may contain parent-child components/directives or they could be siblings components/directives.

I love the concept of modularising them but I have exactly no idea how I can let them communicate with each other. For parent-child directives/components, I understand I can use includes/requires.

But if I had a sibling components, eg a preloader and a carousel gallery component, I can't find any way to let them talk to each other. I suspect that my understanding of the approach and the architecture is totally wrong.

Please enlighten me and finally put me in the right direction of how to tackle this situation.

Thanks guys.

Since 1.5 there are components . As you can read in the docs, they should have only INs (denoted by < binding) and OUTs ( & ).

When you want two sibling components to communicate, you have to do this by some parent component which will assign one component's OUT to another's IN. See a simple example:

 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> 

Of course, there are other options (events or services as you mentioned). But this is a preferred one (IMO) as it maintains single-responsibility components and does not expose their internal implementations (you have noticed I had given different name for the same result in each "scope", havent' you?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM