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.

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);

1 Comment

Thanks for this, however I'm unsure if this is possible with my situation. I have updated my question with more information.
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) {

  });

1 Comment

We don't have two controllers. I have updated the initial question with a little bit more information. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.