javascript - Understanding the AngularJS Approach to component-based architecture -
recently dived project using angularjs , found myself in world of mess. having hard time trying understand how angular should applied project.
a little background project, have multiple sections needs loaded @ start. think of spa has tall content multiple sections.
in these sections, i'm trying include components/directives. may contain parent-child components/directives or siblings components/directives.
i love concept of modularising them have no idea how can let them communicate each other. parent-child directives/components, understand can use includes/requires.
but if had sibling components, e.g. preloader , carousel gallery component, can't find way let them talk each other. suspect understanding of approach , architecture totally wrong.
please enlighten me , put me in right direction of how tackle situation.
thanks guys.
since 1.5 there components. can read in docs, should have ins (denoted <
binding) , outs (&
).
when want 2 sibling components communicate, have parent component assign 1 component's out another's in. see 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 component a. {{ $ctrl.mydata ? "have finished loading" : "am loading" }} data.</p>', controller: function($timeout) { var self = this; $timeout(function() { self.mydata = 'this result'; self.onsometaskfinish({ result: self.mydata }); }, 2000); } }) .component('componentb', { bindings: { 'pricelessresult': '<' }, template: '<p>this component b. {{ !$ctrl.pricelessresult ? "am waiting result" : "have received result! " + $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 other options (events or services mentioned). preferred 1 (imo) maintains single-responsibility components , not expose internal implementations (you have noticed had given different name same result in each "scope", havent' you?).