How to pass data between sibling components without using $scope?

后端 未结 3 1704
深忆病人
深忆病人 2020-11-27 11:08

I am making a component that contains 3 child components in this way:




相关标签:
3条回答
  • 2020-11-27 11:36

    Component approach

    I would suggest you to align with Angular 2 component approach and use inputs/outputs approach. If you do so, you will be able to easily migrate to Angular 2, because components will be conceptually identical (with difference only in syntax). So here is the way you do it.

    So we basically want header and main components to share piece of state with header to be able to change it. There are several approaches we can use to make it work, but the simplest is to make use of intermediate parent controller property. So let's assume parent controller (or component) defines this view property you want to be used by both header (can read and modify) and main (can read) components.

    Header component: input and output.

    Here is how simple header component could look like:

    .component('headerComponent', {
      template: `
        <h3>Header component</h3>
        <a ng-class="{'btn-primary': $ctrl.view === 'list'}" ng-click="$ctrl.setView('list')">List</a>
        <a ng-class="{'btn-primary': $ctrl.view === 'table'}" ng-click="$ctrl.setView('table')">Table</a>
      `,
      controller: function() {
        this.setView = function(view) {
          this.view = view
          this.onViewChange({$event: {view: view}})
        }
      },
      bindings: {
        view: '<',
        onViewChange: '&'
      }
    })
    

    The most important part here is bindings. With view: '<' we specify that header component will be able to read outer something and bind it as view property of the own controller. With onViewChange: '&' components defined outputs: the channel for notifying/updating outer world with whatever it needs. Header component will push some data through this channel, but it doesn't know what parent component will do with it, and it should not care.

    So it means that header controller can be used something like

    <header-component view="root.view" on-view-change="root.view = $event.view"></header-component> 
    

    Main component: input.

    Main component is simpler, it only needs to define input it accepts:

    .component('mainComponent', {
      template: `
        <h4>Main component</h4>
        Main view: {{ $ctrl.view }}
      `,
      bindings: {
        view: '<'
      }
    })
    

    Parent view

    And finally it all wired together:

    <header-component view="root.view" on-view-change="root.view = $event.view"></header-component>
    <main-component view="root.view"></main-component>
    

    Take a look and play with simple demo.

    angular.module('demo', [])
    
    .controller('RootController', function() {
      this.view = 'table'
    })
    
    .component('headerComponent', {
      template: `
        <h3>Header component</h3>
        <a class="btn btn-default btn-sm" ng-class="{'btn-primary': $ctrl.view === 'list'}" ng-click="$ctrl.setView('list')">List</a>
        <a class="btn btn-default btn-sm" ng-class="{'btn-primary': $ctrl.view === 'table'}" ng-click="$ctrl.setView('table')">Table</a>
      `,
      controller: function() {
        this.setView = function(view) {
          this.view = view
          this.onViewChange({$event: {view: view}})
        }
      },
      bindings: {
        view: '<',
        onViewChange: '&'
      }
    })
    
    .component('mainComponent', {
      template: `
        <h4>Main component</h4>
        Main view: {{ $ctrl.view }}
      `,
      bindings: {
        view: '<'
      }
    })
    <script src="https://code.angularjs.org/1.5.0/angular.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    
    <div class="container" ng-app="demo" ng-controller="RootController as root">
      
        <pre>Root view: {{ root.view }}</pre>
        
        <header-component view="root.view" on-view-change="root.view = $event.view"></header-component>
        <main-component view="root.view"></main-component>
        
    </div>

    Demo: http://plnkr.co/edit/ODuY5Mp9HhbqA31G4w3t?p=info


    Here is a blog post I wrote covering component-based design in details: http://dfsq.info/site/read/angular-components-communication

    0 讨论(0)
  • 2020-11-27 11:38

    Although the parent component approach (passing down data via attributes) is a perfect valid and yet good implementation, we can achieve the same thing in a simpler way using a store factory.

    Basically, data is hold by the Store, which is referenced in both components scope, enabling reactive updates of the UI when the state changes.

    Example:

    angular
        .module('YourApp')
        // declare the "Store" or whatever name that make sense
        // for you to call it (Model, State, etc.)
        .factory('Store', () => {
            // hold a local copy of the state, setting its defaults
            const state = {
                data: {
                  heroes: [],
                  viewType: 'grid'
                }
            };
            // expose basic getter and setter methods
            return {
                get() {
                    return state.data;
                },
                set(data) {
                    Object.assign(state.data, data);
                },
            };
        });
    

    Then, in your components you should have something like:

    angular
        .module('YourApp')
        .component('headerComponent', {
            // inject the Store dependency
            controller(Store) {
                // get the store reference and bind it to the scope:
                // now, every change made to the store data will
                // automatically update your component UI
                this.state = Store.get();
    
                // ... your code
            },
            template: `
                <div ng-show="$ctrl.state.viewType === 'grid'">...</div>
                <div ng-show="$ctrl.state.viewType === 'row'">...</div>
                ...
            `
        })
        .component('mainComponent', {
            // same here, we need to inject the Store
            controller(Store) {
                // callback for the switch view button
                this.switchViewType = (type) => {
                    // change the Store data:
                    // no need to notify or anything
                    Store.set({ viewType: type });
                };
    
                // ... your code
            },
            template: `
                <button ng-click="$ctrl.switchViewType('grid')">Switch to grid</button>
                <button ng-click="$ctrl.switchViewType('row')">Switch to row</button>
                ...
            `
    

    If you want to see a working example, check out this CodePen.

    Doing so you can also enable the communication between 2 or N components. You just only have to:

    1. inject the store dependency
    2. make sure you link the store data to your component scope

    like in the example above (<header-component>).

    In the real world, a typical application needs to manage a lot of data so make more sense to logically split the data domains in some way. Following the same approach you can add more Store factories. For example, to manage the current logged user information plus an external resource (i.e. catalog) you can build a UserStore plus a CatalogStore -- alternatively UserModel and CatalogModel; those entities would also be good places to centralize things like communication with the back-end, add custom business logic, etc. Data management will be then sole responsibility of the Store factories.

    Keep in mind that we're mutating the store data. Whilst this approach is dead simple and clear, it might not scale well because will produce side effects. If you want something more advanced (immutability, pure functions, single state tree, etc.) check out Redux, or if you finally want to switch to Angular 2 take a look at ngrx/store.

    Hope this helps! :)

    You don't have to do it the Angular 2 way because just in case you would migrate sometimes... Do it if it make sense for you to do it.

    0 讨论(0)
  • 2020-11-27 11:41

    Use custom events to achieve this. you can pass message across your application using event dispatchers $emit(name, args); or $broadcast(name, args); And you can listen for this events using method $on(name, listener);

    Hope it helps

    Ref: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit

    Example: you can notify change like below from your header-component

    $rootScope.$emit("menu-changed", "list");
    

    And you can listen for the change in your main-component directive like

    $rootScope.$on("menu-changed", function(evt, arg){
      console.log(arg);
    });
    
    0 讨论(0)
提交回复
热议问题