0

I find myself often writing one service that wrap rest api (ApiService), then another service that wrap some business logic around it (ActionDispatcher), and then I need it in various controllers.

So ControllerA have:

...
$scope.funA = () => { ActionDispatcher.funA() };
$scope.funB = () => { ActionDispatcher.funB() };
$scope.funC = () => { this->funC_reimplemented() };
...

While ControllerB have:

...
$scope.funA = () => { ActionDispatcher.funA() };
$scope.funB = () => { this.funB_reimplemented() };
$scope.funC = () => { ActionDispatcher.funC() };
...

Is there Angular Way for something like?

function ControllerA(...) {
  functionsFrom(ActionDispatcher);
  ...
  $scope.funC = () => { this->funC_reimplemented() };
  ...

functionsFrom desired behavior:

  • Only copy functions (I want my ControllerA and ControllerB to just delegate responsibilities to ActionDispatcher)
  • Attach those new functions to $scope
  • (Optionally) Attach those new functions to provided object (so ControllerA As vm still works)
przemo_li
  • 3,932
  • 4
  • 35
  • 60
  • Possible duplicate of [how angular controller (and scope) inheritance works](http://stackoverflow.com/questions/31640868/how-angular-controller-and-scope-inheritance-works) – Estus Flask Nov 13 '15 at 17:56
  • Nope. Its not. Due to how inheritance of `$scope` works one Controller need to be tied to html element/comment/whatnot placed **inside** other. So whatnot "hosting" `ControllerA` would need to be wrapping whatnow "hosting" `ControllerB`, end even then its one way inheritance. Unrelated to my `ActionDispatcher` service too. – przemo_li Nov 13 '15 at 20:58
  • There's no mention in the original question of what you've just said. Please, provide more code and some information how it is supposed to be used. It is not clear what you're trying to achieve, and the fact that you're sticking to '$scope' instead of 'this' with ES6/TS syntax doesn't add clarity, too. – Estus Flask Nov 13 '15 at 21:08
  • Edited my question. I want to defenitevly forward some of controller functions to service functions. Have nothing to do with `$scope` inheritance. (Or maybe it do, but I do not know how..) – przemo_li Nov 14 '15 at 09:00

1 Answers1

1

I guess it has to be

app.value('bindMethods', (obj) => {
  var boundObj;

  if (angular.isObject(obj)) {
    boundObj = {};
    angular.forEach(obj, (fn, key) => {
      if (typeof fn !== 'function')
        return;
      boundObj[key] = angular.bind(obj, fn);
    });
  }

  return boundObj;
});

function ControllerA(ActionDispatcher, bindMethods) {
  angular.extend($scope, bindMethods(ActionDispatcher));
  // or
  // angular.extend(this, bindMethods(ActionDispatcher));
  ...

Wrapping them in closures will require additional measures for passing arguments, that's essentially the job that angular.bind does (which in its turn provides a replacement for native Function.prototype.bind).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565