0

Hello I have code like this

<section>
  <component1></component1>
  <component2></component2>
</section>

And now in component1 I have action for save form like this

export default function Component1Controller() {
  this.save = save.bind(this);
  function save(valid) {
    // save magic
  }
}

And if is saved then I want to update view in second controller

export default function Component2Controller() {;
 function update() {
   //run update when component1 saved data
 }
}

Its possible to do this without function $on or $watch ? any sugestions?

axlpl
  • 483
  • 1
  • 7
  • 18
  • Use bindings, e.g. one-way (`"<"`) bindings for inputs; expression (`"&"`) bindings for outputs. For more information, see [AngularJS Developer Guide - Component-based application architecture](https://docs.angularjs.org/guide/component#component-based-application-architecture). – georgeawg Aug 23 '18 at 23:37

1 Answers1

0

Sure. I don't have your exact example to work with, so this is of course a generalized solution. I won't type out the whole service, but here are the methods:

// service setup...

const service = this;

service.registeredComponents = {};

service.register = (id, func) => {
  service.registeredComponents[id] = func;
};

service.callAllRegistered = (options /* whatever you want to pass */) => {
  Object.keys(service.registeredComponents).forEach((key) => service.registeredComponents[key](options));
};

service.deregister = (id) => {
  service.registeredComponents[id] = () => {};
  // or just delete the id, I did this instinctually, but you dont have to
}

This is a very simple observable pattern that is useful is many scenarios. I believe you should have no issue adapting that to your use-case. You can inject that service into any component, register its 'update' method, then call all registered 'update' methods from any other component. Don't forget to deregister any 'update' methods of components when they are destroyed.

Devin Fields
  • 2,066
  • 1
  • 10
  • 18
  • Instead of re-inventing observable objects, Angular 2+ uses RxJS. To make the migration to Angular 2+ easier use them here. See [Push Values from a Service with RxJS](https://stackoverflow.com/a/35535336/5535245) – georgeawg Aug 23 '18 at 23:55
  • Thanks for posting that; however, the poster might never plan on migrating this project to A2+, and while yes, he could use RxJS, if his use-case is simple enough, I don't see any reason to, especially since he still has to write much of this code, as shown in the RxJS example. – Devin Fields Aug 24 '18 at 14:24