2

I am trying to work out the best way to call a function inside an AngularJS controller, from outside the controller.

We are using a Python backend, which sends back data to the frontend via JavaScript functions. I am using this at the moment to send that data into the Angular controller...

function myFunction(var1, var2) {
    angular.element($('body')).scope().insideFunction(var1, var2);
}

This works very well, but I'm just wondering if this is the best way to do this.

Edit: I have rolled with this, and have about 8 of these "outside scope" functions working fine. The data simply gets passed from Python > JS function > Angular function.

If anyone has a better method of doing this, I would love to hear it.

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
Andy92
  • 141
  • 1
  • 11

3 Answers3

1

It may work well but it's not the best way of doing it.

If you want to communicate between controllers, you can use events. More details are available here:

https://stackoverflow.com/a/14502755/4693496

Community
  • 1
  • 1
Erazihel
  • 7,295
  • 6
  • 30
  • 53
  • 1
    Thank you, however we are not communicating between controllers. I have added more info to my question. Our python backend can only call JS functions, therefore I'm looking for the best way to get that data into my controller. – Andy92 Jul 19 '15 at 18:53
0

Use 'controller as' syntax:

html:
<div ng-app="demo" ng-controller="MainController as main">
    <button ng-click="main.insideFunction()"></button>
</div>

js:
function MainController() {}

MainController.prototype.insideFunction = function() {};

angular.module('demo', [])
  .controller('MainController', MainController);

MainController.prototype.insideFunction(var1, var2);
monkey
  • 1,279
  • 14
  • 15
  • Thanks for this, however I'm unsure if this is possible with my situation. I have updated my question with more information. – Andy92 Jul 19 '15 at 21:19
0

Instead of directly calling a controller inside another controlller. You can expose the data in your first controller via the global $rootScope object,

You can define your variable on the $rootScope global object and have it become accessable inside any controller.

<body>
    <div ng-controller="ctrl1">
      {{name}}
    </div>
    <div ng-controller="ctrl2">
      {{name}}
    </div>
  </body>



 var app = angular.module('plunker', []);
  app.controller('ctrl1', function($rootScope, $scope) {
      $rootScope.name = "jACK";
  });

  app.controller('ctrl2', function($rootScope, $scope) {

  });
pro
  • 792
  • 7
  • 30
  • We don't have two controllers. I have updated the initial question with a little bit more information. Thanks for your help. – Andy92 Jul 19 '15 at 19:19