0

I've got a controller with a http request, and I need to call it from another controller, this is the controller i need to launch:

app.controller('getDataCtrl', function ($scope, $http, $ionicLoading) {
$scope.request = $http({
    method: "POST",        
    url: "someurl",
    dataType: "json",
    contentType: "application/json; charset=utf-8"
}).then(function mySucces(response) {
    $scope.allTracks = response.data;
    $scope.recentTracks = response.data.Tracks;
}

and this is how i tried to call it:

angular.element(document.getElementById('getDataCtrl')).$scope.$apply();
1
  • 4
    This is an XY Problem and idea doesn't make any sense. Use a service to share methods across the app Commented May 14, 2017 at 11:26

1 Answer 1

1

You can use event broadcasting to communicate between controllers :

angular.module('app', []);

angular.
module('app')
  .controller('FirstController', ['$scope', '$rootScope', function($scope, $rootScope) {
    $scope.test = function() {
      // broadcast custom event with some data
      // OR do something with a shared service
      //
      // SomeService.doSomething().then(function() {
      //   $rootScope.$broadcast("SOME_EVENT");
      // });
      //
      $rootScope.$broadcast("SOME_EVENT", "someValue");
    };
  }])
  .controller('SecondController', ['$scope', '$rootScope', function($scope, $rootScope) {
    // Listen for custom event
    $rootScope.$on("SOME_EVENT", function(event, data) {
      // Call controller function
      $scope.updateData(data);
    })
    // Do whatever you want here
    $scope.updateData = function(data) {
      // MyService.doSomethingElse().then(function() {
      //   ...
      //});
      $scope.data = data;
    }
  }]);
<!doctype html>

<html lang="en" ng-app="app">

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<div ng-controller="FirstController">
  <button ng-click="test()">Test</button>
</div>
<div ng-controller="SecondController">
  <pre>{{ data }}</pre>
</div>

</html>

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

Comments

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.